21xrx.com
2024-09-20 00:54:00 Friday
登录
文章检索 我的文章 写文章
C++:提取字符串中的数字
2023-07-05 07:12:34 深夜i     --     --
C++ 字符串 数字 提取

C++是一门常用的编程语言,提取字符串中的数字也是其常见用法之一。在C++中,基本数据类型包括int,float,double等,这些数据类型表示数字。但对于字符串类型,C++中没有直接提取数字的方法,需要使用一些技巧来实现。

首先,可以使用字符串的find_first_of()和find_last_of()方法来查找数字在字符串中出现的位置。这两个方法分别返回第一个和最后一个匹配到的字符的位置。可以通过循环和转换将这些数字提取出来。例如,以下代码可以提取“abc123def”字符串中的数字:


#include <iostream>

#include <string>

using namespace std;

int main() {

  string str = "abc123def";

  int pos = 0;

  string num = "";

  while ((pos = str.find_first_of("0123456789", pos)) != string::npos) {

    num += str[pos];

    pos++;

  }

  int n = stoi(num);

  cout << n << endl;

  return 0;

}

该代码使用find_first_of()在字符串中查找数字的位置,如果找到了数字,就将其添加到一个新的字符串num中。最后,使用stoi()函数将字符串转换为整数。输出结果为“123”。

另外,如果字符串中包含多个数字,则可以使用正则表达式来提取。C++的正则表达式库regex提供了一些方法来处理字符串中的数字。例如,以下代码可以提取“123abc456def”字符串中的数字:


#include <iostream>

#include <string>

#include <regex>

using namespace std;

int main() {

  string str = "123abc456def";

  regex reg("\\d+");

  smatch match;

  string num = "";

  while (regex_search(str, match, reg)) {

    num += match.str();

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

  }

  int n = stoi(num);

  cout << n << endl;

  return 0;

}

该代码使用regex_search()方法在字符串中查找数字。如果找到了数字,就将其添加到一个新的字符串num中。最后,使用stoi()函数将字符串转换为整数。输出结果为“123456”。

在C++中提取字符串中的数字需要使用基本库函数以及一些技巧。通过以上方法,我们可以很方便地处理字符串中的数字,实现自己的功能。

  
  

评论区

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