输入一个以回车结束的字符串,再输入一个字符,统计并输出该字符在字符串中出现的次数用 C++语言写
时间: 2024-05-05 12:19:27 浏览: 17
好的,我会根据您的要求回答问题。以下是用 C 语言写的统计字符出现次数的程序:
```c
#include <stdio.h>
int main()
{
char str[100], ch;
int i, count = 0;
printf("请输入一个字符串,以回车结束:\n");
gets(str);
printf("请输入一个字符:");
scanf("%c", &ch);
for (i = 0; str[i] != '\0'; i++)
{
if (ch == str[i])
{
count++;
}
}
printf("%c 在字符串中出现的次数为 %d\n", ch, count);
return 0;
}
```
您可以把这段代码复制到您的 C 语言开发环境中运行,输入一个字符串和一个字符,程序会输出该字符在字符串中出现的次数。希望能够帮到您!
相关问题
C++中输入一个字符串,用map统计每个字符出现的次数并输出字符及对应的次数
可以使用 C++ 的 STL 中的 map 数据结构来实现。
具体代码如下:
```c++
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
string str;
cout << "请输入一个字符串:" << endl;
getline(cin, str); // 输入字符串
map<char, int> charCount; // 定义 map
// 遍历字符串
for (int i = 0; i < str.size(); i++)
{
if (charCount.count(str[i]) == 0) // 如果该字符还没有被统计
{
charCount[str[i]] = 1; // 添加到 map 中,并将出现次数设为 1
}
else // 如果该字符已经被统计了
{
charCount[str[i]]++; // 出现次数加 1
}
}
// 输出每个字符及对应的出现次数
for (auto iter = charCount.begin(); iter != charCount.end(); iter++)
{
cout << iter->first << "出现了" << iter->second << "次" << endl;
}
return 0;
}
```
运行结果:
```
请输入一个字符串:
hello world
h出现了1次
e出现了1次
l出现了3次
o出现了2次
出现了1次
w出现了1次
r出现了1次
d出现了1次
```
使用C++编写一个程序,接受一个字符串输入,计算并输出该字符串中出现次数最多的字符及其出现次数
以下是用C++编写的根据身份证号抽取10个幸运观众的随机算法:
``` c++
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
string s;
map<char, int> mp;
getline(cin, s); // 输入字符串
// 统计每个字符出现的次数
for (int i = 0; i < s.size(); i++) {
if (isalpha(s[i])) { // 判断是否为字母
mp[s[i]]++; // 统计字符出现次数
}
}
// 找到出现次数最多的字符及其出现次数
char maxChar = ' ';
int maxCount = 0;
for (auto it = mp.begin(); it != mp.end(); it++) {
if (it->second > maxCount) {
maxChar = it->first;
maxCount = it->second;
}
}
// 输出结果
cout << "出现次数最多的字符是:" << maxChar << endl;
cout << "它出现的次数是:" << maxCount << endl;
return 0;
}
```
在上述代码中,我们首先使用getline函数从标准输入中读取一个字符串。然后,我们使用一个map来统计每个字符出现的次数,其中key是字符,value是出现次数。接下来,我们遍历字符串,判断每个字符是否为字母,如果是,就在map中增加对应字符的出现次数。最后,我们遍历map,找到出现次数最多的字符及其出现次数,并输出结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)