当前位置:首页 C++ > 正文

c++提取字符串中的数字

作者:野牛程序员:2023-07-18 09:32:27 C++阅读 2778

要提取字符串中的数字,你可以使用C++标准库中的字符串处理函数和正则表达式库。下面是使用两种方法的示例代码:

方法一:使用字符串处理函数

#include <iostream>
#include <string>
#include <cctype>

int main() {
    std::string str = "abc123def456ghi";
    std::string digits = "";

    for (char c : str) {
        if (std::isdigit(c)) {
            digits += c;
        }
    }

    std::cout << "提取的数字为: " << digits << std::endl;

    return 0;
}

输出:

提取的数字为: 123456

方法二:使用正则表达式

#include <iostream>
#include <string>
#include <regex>

int main() {
    std::string str = "abc123def456ghi";
    std::regex regex("\\\\d+"); // 匹配一个或多个数字

    std::smatch match;
    std::string digits = "";

    // 使用迭代器遍历匹配结果
    auto words_begin = std::sregex_iterator(str.begin(), str.end(), regex);
    auto words_end = std::sregex_iterator();
    for (std::sregex_iterator it = words_begin; it != words_end; ++it) {
        digits += (*it).str();
    }

    std::cout << "提取的数字为: " << digits << std::endl;

    return 0;
}

输出:

提取的数字为: 123456

以上两种方法都可以提取字符串中的数字。第一种方法使用了一个循环,逐个字符检查是否为数字,如果是数字则将其添加到结果字符串中。第二种方法使用了正则表达式 \\d+ 来匹配一个或多个数字,并使用迭代器遍历所有匹配结果,将其添加到结果字符串中。可以根据需要选择适合你的情况的方法。

野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击