C++中提取字符串中的连续数字
时间: 2023-12-06 20:38:50 浏览: 205
以下是C++中提取字符串中的连续数字的方法:
方法一:使用isdigit()函数和stringstream类
```cpp
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
void extractNumbers(string str, int* arr, int& count) {
stringstream ss(str);
string temp;
while (ss >> temp) {
int num = 0;
for (int i = 0; i < temp.length(); i++) {
if (isdigit(temp[i])) {
num = num * 10 + (temp[i] - '0');
}
else {
if (num != 0) {
arr[count++] = num;
num = 0;
}
}
}
if (num != 0) {
arr[count++] = num;
}
}
}
int main() {
string str = "abc2345 345fdf678 jdhfg945";
int arr[100];
int count = 0;
extractNumbers(str, arr, count);
for (int i = 0; i < count; i++) {
cout << arr[i] << " ";
}
cout << endl;
cout << "共有" << count << "个整数" << endl;
return 0;
}
```
方法二:使用正则表达式
```cpp
#include <iostream>
#include <string>
#include <regex>
using namespace std;
void extractNumbers(string str, int* arr, int& count) {
regex reg("\\d+");
smatch result;
while (regex_search(str, result, reg)) {
arr[count++] = stoi(result[0]);
str = result.suffix().str();
}
}
int main() {
string str = "abc2345 345fdf678 jdhfg945";
int arr[100];
int count = 0;
extractNumbers(str, arr, count);
for (int i = 0; i < count; i++) {
cout << arr[i] << " ";
}
cout << endl;
cout << "共有" << count << "个整数" << endl;
return 0;
}
```
阅读全文