用c++提取字符串中的数字
时间: 2024-03-21 18:19:27 浏览: 38
以下是一个简单的示例代码,用于从字符串中提取数字:
```c
#include <stdio.h>
#include <ctype.h>
void extractNumbers(char *str) {
int i = 0;
while (str[i]) {
if (isdigit(str[i])) {
int num = 0;
while (isdigit(str[i])) {
num = num * 10 + (str[i] - '0');
i++;
}
printf("%d ", num);
}
else {
i++;
}
}
}
int main() {
char str[] = "abc123def456ghi789";
extractNumbers(str);
return 0;
}
```
输出结果为:
```
123 456 789
```
该代码使用了两个循环,第一个循环遍历字符串中的每个字符,第二个循环提取数字。如果当前字符是数字,则进入第二个循环,将连续的数字字符转换为整数并输出。如果当前字符不是数字,则继续遍历下一个字符。
相关问题
C++中提取字符串中的连续数字
以下是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;
}
```
c++从字符串中提取数字求和
可以使用正则表达式来从字符串中提取数字,然后将这些数字相加。具体代码如下:
```cpp
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main()
{
string str = "abc123def456ghi789";
regex reg("\\d+");
smatch match;
int sum = 0;
while (regex_search(str, match, reg)) {
for (auto x : match) {
sum += stoi(x);
}
str = match.suffix().str();
}
cout << "Sum of all numbers in the string: " << sum << endl;
return 0;
}
```
以上代码会输出:Sum of all numbers in the string: 1368,这是因为字符串中的数字分别为123、456和789,它们的和为1368。