在字符串中搜索数字

Searching for numbers in a string

本文关键字:数字 搜索 字符串      更新时间:2023-10-16

用户以的形式输入字符串

长度=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;
}