我正在尝试制作一个程序来计算字符串中每个字符的出现次数,如下所示:
Enter string: hello world
输出为
h: 1
e: 1
l: 3
o: 2
......等等
但我的输出似乎到处都是,例如:
Enter string: nice on ice
n: 2
i: 2
c: 1
e: 1 //there should be 2 e's
o: 1
有时喜欢:
Enter string: potato
p: 1
o: 2
t: 2
a: 1
: 1
这是我的代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main() {
char l, str[30], cpy[30];
int i, j, occ;
i = j = 0;
occ = 0;
cout << "Enter string: ";
fgets(str, 10, stdin);
strcpy(cpy, str); // copy the string as I am about to modify it
// Checks for occurences of each character.
// Every character found is changed to a ' ' so that it isn't counted again
while (str[i] != '\0') {
occ = 0;
if (str[i] != ' ') {
l = str[i];
for (j = 0; str[j] != '\0'; j++) {
if (str[j] == cpy[i] && str[j] != ' ') {
occ++;
str[j] = ' ';
}
}
cout << l << ": " << occ <<endl;
}
i++;
}
cout << "\n";
fputs(str, stdout); // just to check if all characters were converted to ' '
cout << "\n";
return 0;
}
答案 0 :(得分:0)
你真的不需要复制,你的内循环做了太多的工作,迭代已经失效的字符。另外,您似乎对于i
或j
是否将副本或原始内容编入索引感到困惑。
int main()
{
char str[30];
int i, j, occ;
cout << "Enter string: ";
fgets(str, 10, stdin);
// Checks for occurences of each character.
// Every character found is changed to a ' ' so that it isn't counted again
for(i = 0; str[i] != '\0'; i++)
{
if (str[i] != ' ')
{
// Output the current character before it is invalidated.
cout << str[i] << ": ";
// Start at the current character so that it is counted
// at least once.
occ = 0;
for (j = i; str[j] != '\0'; j++)
{
// No need to test for ' ', because str[i] is not
// a ' ', so equality is sufficient.
if (str[j] == str[i])
{
occ++;
// Invalidate each counted character.
str[j] = ' ';
}
}
cout << occ << endl;
}
}
// just to check if all characters were converted to ' '
cout << endl << str << endl;
return 0;
}
答案 1 :(得分:0)
对于您的作业的可能解决方案,请记住英文字母中有26个字母,将每个字母转换为数组的索引很简单(ASCII encoding它是非常简单。)
有了这些信息,请考虑使用26个整数数组,其中数组中的每个元素都是您读取的字符的计数器。
因此,只需在循环中一次读取一个字符,从字符中获取反数组索引,并增加正确的元素。无需实际存储您阅读的文本,无需多次检查循环。
打印时,循环遍历数组并打印每个非零元素及其相应的字符。