用c++写统计某个字符在字符串中出现的次数
时间: 2023-10-18 21:04:21 浏览: 506
可以使用 C++ 的字符串(string)类和循环结构实现统计某个字符在字符串中出现的次数。具体实现如下:
```cpp
#include <iostream>
#include <string>
using namespace std;
int countChar(string str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str[i] == c) {
count++;
}
}
return count;
}
int main() {
string str = "Hello, World!";
char c = 'o';
int count = countChar(str, c);
cout << "The character '" << c << "' appears " << count << " times in the string." << endl;
return 0;
}
```
在上面的代码中,我们定义了一个 `countChar` 函数,它接收两个参数:一个字符串和一个字符。该函数使用循环结构遍历字符串中的每个字符,如果当前字符等于要统计的字符,就将计数器加 1。最后,函数返回计数器的值。
在 `main` 函数中,我们定义了一个字符串 `str` 和一个字符 `c`,然后调用 `countChar` 函数统计字符 `c` 在字符串 `str` 中出现的次数,并将结果输出到控制台。