在字符串中搜索数字
Searching for numbers in a string
用户以的形式输入字符串
长度=10宽度=15
任务是在这样的字符串中找到长度和宽度的值(并将它们分配给变量)。那么,我怎样才能找到这两个数字呢?我应该使用什么功能/方法?你们能给我个主意吗?
正则表达式很有趣,通常不能作为入门课程的家庭作业解决方案。
match[1]
和match[2]
是您感兴趣的字符串的数字部分。如果需要将它们作为整数进行操作,您可能需要将它们传递给stoi()
。
代码
#include <iostream>
#include <regex>
int main() {
std::string s("length=10 width=15");
std::regex re("length=([0-9]+) width=([0-9]+)");
std::smatch match;
if (regex_match(s, match, re)) {
std::cout << "length: " << match[1] << "n";
std::cout << "width: " << match[2] << "n";
}
}
输出
length: 10
width: 15
使用字符串流:
#include <string>
#include <iostream>
#include <sstream>
#include <map>
using namespace std;
int main()
{
stringstream ss;
ss.str("length1=10 width=15 length2=43543545");
map<string, int> resMap;
string key;
int val;
while (ss.peek() != EOF) {
if (isalpha(ss.peek())) {
char tmp[256];
ss.get(tmp,streamsize(256),'=') ;
key = tmp;
} else if (isdigit(ss.peek())) {
ss >> val;
resMap.insert(pair<string, int>(key,val));
} else {
ss.get();
}
}
cout << "result:n";
for (map<string, int>::iterator it = resMap.begin(); it != resMap.end(); ++it) {
cout << "resMap[" << it->first<< "]=" << it->second << endl;
}
getchar();
return 0;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 搜索字符串是否至少包含一次从 0 到 9 的所有数字的最有效方法
- 使用二叉搜索查找数字的第 N 次出现的索引
- C 搜索数组以获取一个数字,但如果找不到该数组,则不会触发其他语句
- C 搜索算法第一个数字= n
- 如何在较高和较低数字的阵列中适应搜索算法(3N / 2)-2
- 在不进行线性搜索的情况下,在非常大的数组中找到比给定数字更小的数字
- 在字符串中的一行中搜索大于0的数字
- 在字符串中搜索数字
- 使用cctype库搜索函数,以查找某个范围内的数字字符数
- 二叉搜索以查找数字所在的范围
- 在未排序的数组中搜索一个数字
- C++搜索数组中最大的数字
- 在C++中存储和搜索数字的最佳方式
- 给定一个二叉搜索树和一个数字,找到一个路径,其节点的数据被添加为给定的数字。
- 在N个未排序的数字中搜索给定值的最佳方法
- 使用指针和线性搜索在数组中找到较大和最小的数字
- 在c++中,检查一个数字是否已经添加到列表中,而不需要暴力搜索该列表
- std::string 搜索字符串中的数字并在前后插入空格
- 如何在文件中搜索数字