C加加中在一串字符串中找出数字并数出数量
时间: 2024-02-15 12:01:28 浏览: 32
在 C++ 中,可以使用正则表达式来匹配字符串中的数字。具体实现可以使用 C++11 引入的 `<regex>` 库。
下面是一个示例代码,可以在一段字符串中找出数字并计算数量:
```c++
#include <iostream>
#include <regex>
using namespace std;
int main()
{
string str = "abc123def456ghi789";
regex pattern("\\d+");
smatch match;
int count = 0;
while (regex_search(str, match, pattern)) {
count++;
str = match.suffix().str();
}
cout << "The number of digits in the string is: " << count << endl;
return 0;
}
```
输出结果为:
```
The number of digits in the string is: 3
```
其中,`\\d+` 表示匹配一个或多个数字字符,`regex_search` 函数可以在字符串中查找匹配的子串。`match.suffix().str()` 表示从当前匹配的子串之后的字符串中继续查找。
相关问题
用C加加语言采用指针输入字符串并在屏幕上打印
下面是一个用 C++ 语言编写的函数,该函数采用指针输入字符串并在屏幕上打印:
```cpp
#include <iostream>
using namespace std;
void printString(char *str) {
while (*str != '\0') {
cout << *str;
str++;
}
cout << endl;
}
int main() {
char str[] = "Hello, World!";
printString(str);
return 0;
}
```
在这个函数中,我们使用了一个指针来迭代字符串中的每个字符。while 循环在字符串的末尾遇到空字符时停止,然后我们打印出整个字符串并在最后添加一个换行符。
在主函数中,我们声明了一个字符数组 str 并将其初始化为 "Hello, World!"。然后,我们调用 printString 函数,并将 str 的地址作为参数传递给它。最后,我们在主函数中返回 0。
运用C加加编写一个程序输入一个字符串求字符串中字符的个数并输出
以下是一个简单的 C++ 程序,可以实现输入一个字符串,统计其中的字符个数并输出:
```c++
#include <iostream>
#include <string>
int main() {
std::string str;
std::cout << "请输入一个字符串:" << std::endl;
std::getline(std::cin, str);
int count = 0;
for (int i = 0; i < str.size(); i++) {
if (str[i] != ' ') { // 排除空格
count++;
}
}
std::cout << "字符个数为:" << count << std::endl;
return 0;
}
```
这个程序中,首先使用 `std::getline()` 函数读入一行字符串,然后遍历字符串中的每个字符,如果不是空格,则计数器加 1。最后输出字符个数即可。