计算C++中每个字母表的出现次数
Count the appearance of each alphabet in C++
我正在尝试用c++编写一段代码,该代码接受用户的字符串输入,并按字母顺序排列字符串。现在我想扩展这段代码,给我输出"a"出现的次数等等,但我无法扩展它。可能有很多方法可以处理这个问题,但如果有人能指导我如何使用数组处理这个问题的话,请告诉我。
#include <iostream>
#include <sstream>
#include <string>
#include <map>
using namespace std;
int main()
{
cout << " please enter your charactor " << endl;
string ch;
getline(cin, ch);
int i, step, temp;
for (step = 0; step<ch.size() - 1; ++step)
for (i = 0; i<ch.size()- step - 1; ++i)
{
tolower(ch[1]);
if (tolower(ch[i])>tolower(ch[i + 1]))
{
temp = ch[i];
ch[i] = ch[i + 1];
ch[i + 1] = temp;
}
}
// count the appearance of each letter using array
cout << " total lenght of your string's charactor is " << ch.length() << endl;
system("pause");
}
这就是您所需要的
#include <iostream>
#include <string>
using namespace std;
int main()
{
// you could easily use a vector instead of an array here if you want.
int counter[26]={0};
string my_string = "some letters";
for(char c : my_string) {
if (isalpha(c)) {
counter[tolower(c)-'a']++;
}
}
// thanks to @James
for (int i = 0; i < 26; i++)
{
cout << char('a' + i) << ": " << counter[i] << endl;
}
}
从字符中减去CCD_ 1将字母CCD_。打印回时,可以将字母'a'
添加回该位置。
使用基于范围的for循环需要c++11,但也可以使用传统的for循环。
从技术上讲,这只适用于字母表中26个或更少字母的语言。。。
相关文章:
- 如何在C++中移动字母表中的字母?
- 循环回到z之后的字母表的开头
- C 分类字符串按大小和字母表
- 我在使用布尔函数时遇到问题,其中用户输入两个字母并输出字母表中最高的字母
- 使用列表向后打印字母表时缺少'a'
- 警告:数组"字母表"由括号字符串文本初始化
- 如何检查字符是否是某个字母表中的字母
- 为什么在此 C 代码中将字母表拆分为多个范围?
- c++如何确定字母表中一个单词是否在另一个单词之前
- 计算C++中每个字母表的出现次数
- 求字母表{a,b,c}上长度为n的字符串w的个数
- 如何检查字母表中的字母在文本文件中出现的次数C++
- 将莫尔斯值解码为字母表
- 在 C 语言中,求解从字母表中输入的整数并重复循环
- 迭代C/C++中的字母表
- 制作一个程序来计算字母表中每个字母的出现次数
- C++编程中的字母表到星形
- 按字母表对字符串数组进行排序并显示值
- 找出字母表中一个字母对应的数字
- 土耳其字母表的凯撒密码解密