21xrx.com
2024-09-19 08:15:23 Thursday
登录
文章检索 我的文章 写文章
C++中如何查找字符串中的数字
2023-07-13 16:59:21 深夜i     --     --
C++ 查找 字符串 数字

在C++中,字符串是一个常见的数据类型。在处理字符串的过程中,有时候需要从字符串中找出数字。在这篇文章中,我们将介绍一些方法来实现这一点。

1.使用isdigit()函数

isdigit()函数是一个C++标准库函数,用于检查给定的字符是否是数字字符。可以将这个函数结合使用一个for循环,检查每个字符是否是数字字符,从而找出字符串中的数字。

例如,下面的代码片段能够找出一个字符串中的所有数字:


#include <iostream>

#include <string>

using namespace std;

int main()

{

  string str = "abc123def456";

  string digits;

  for(int i = 0; i < str.size(); i++)

  {

    if(isdigit(str[i]))

    {

      digits += str[i];

    }

  }

  cout << digits << endl; // 输出:123456

  return 0;

}

2.使用stringstream

stringstream是一个C++标准库中的类,用于将字符串转换为其他类型的数据。将一个字符串传递给stringstream对象,然后使用提取运算符(>>)从中提取数字。这个方法可以处理包含数字以外的其他字符的字符串

例如,下面的代码片段可以找出字符串中的所有数字:


#include <iostream>

#include <string>

#include <sstream>

using namespace std;

int main()

{

  string str = "abc123def456";

  string digits;

  stringstream ss(str);

  char ch;

  while(ss >> ch)

  {

    if(isdigit(ch))

    {

      digits += ch;

    }

  }

  cout << digits << endl; // 输出:123456

  return 0;

}

3.使用正则表达式

正则表达式是一种强大的工具,可以轻松地从字符串中找出需要的内容。C++中的regex库提供了一个regex_search函数,可以搜索包含指定字符模式的字符串。

例如,下面的代码片段使用regex_search函数查找字符串中的所有数字:


#include <iostream>

#include <string>

#include <regex>

using namespace std;

int main()

{

  string str = "abc123def456";

  string digits;

  regex pattern("(\\d+)");

  smatch match;

  while(regex_search(str, match, pattern))

  {

    digits += match[0];

    str = match.suffix().str();

  }

  cout << digits << endl; // 输出:123456

  return 0;

}

总的来说,以上三种方法都可以有效地从字符串中找出数字。大家可以根据不同的需求选择不同的方法来实现。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复