c++函数怎么统计字符个数
作者:野牛程序员:2023-08-26 16:42:39 C++阅读 2890
使用C++编写一个统计字符个数的函数可以这样做:
#include <iostream>
#include <string>
int countCharacters(const std::string &str, char targetChar) {
int count = 0;
for (char c : str) {
if (c == targetChar) {
count++;
}
}
return count;
}
int main() {
std::string inputString;
char targetCharacter;
// 获取输入的字符串和目标字符
std::cout << "请输入一个字符串:";
std::cin >> inputString;
std::cout << "请输入要统计的目标字符:";
std::cin >> targetCharacter;
// 调用函数统计字符个数并输出结果
int charCount = countCharacters(inputString, targetCharacter);
std::cout << "字符 '" << targetCharacter << "' 在字符串中出现的次数为:" << charCount << std::endl;
return 0;
}在这段代码中,countCharacters 函数接受一个字符串和一个目标字符作为参数,然后遍历字符串的每个字符,如果字符与目标字符相同,则计数器增加。最后,main 函数获取用户输入的字符串和目标字符,调用 countCharacters 函数进行统计,并输出结果。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:将从arduino接收的字符串数据转换为整数或浮点数
- 下一篇:C++统计有效字符数
