写出一个程序,接受一个由字母、数字和空格组成的字符串,和一个字符,然后输出输入字符串中该字符的出现次数。(不区分大小写字母)用c++实现
时间: 2024-04-08 10:30:46 浏览: 23
当然,下面是一个用C++实现的程序,可以接受一个由字母、数字和空格组成的字符串,并且统计其中某个字符出现的次数(不区分大小写字母):
```cpp
#include <iostream>
#include <string>
#include <cctype>
int countCharacterOccurrences(const std::string& str, char ch) {
int count = 0;
char lowercaseCh = std::tolower(ch); // 将目标字符转换为小写字母
for (char c : str) {
if (std::tolower(c) == lowercaseCh) { // 将当前字符转换为小写字母并与目标字符比较
count++;
}
}
return count;
}
int main() {
std::string inputString;
char targetCharacter;
// 获取输入字符串和目标字符
std::cout << "请输入一个由字母、数字和空格组成的字符串:" << std::endl;
std::getline(std::cin, inputString);
std::cout << "请输入一个字符:" << std::endl;
std::cin >> targetCharacter;
// 统计目标字符出现的次数
int occurrenceCount = countCharacterOccurrences(inputString, targetCharacter);
// 输出结果
std::cout << "目标字符出现的次数为:" << occurrenceCount << std::endl;
return 0;
}
```
你可以通过在终端运行该程序并按照提示输入相应的字符串和字符来测试它。程序会输出目标字符在输入字符串中出现的次数。请注意,该程序不会考虑非字母、数字和空格的字符。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)