【发布时间】:2016-12-01 16:52:31
【问题描述】:
我试图显示用户选择的句子中的哪个字符以及每个字符有多少。因此,如果用户输入“Hello World!”程序应返回一个字符及其使用次数。
" SPACE:1, !:1, H:1, W:1, e:1, d:1, l:3, o:2, r:1,"
我将它放在一个开关中,因为我有其他选择供用户选择。
现在我可以找出使用的字符以及从 SPACE 到 Q 有多少个。我也可以找出所有的小写字母,但如果它读到“a”,它会说有 1 个“a” ' 和一个空格(在 ASCII 码中,它从 32 开始,随着小写字母的上升而上升)。
这些是我使用的变量。
int menyval = 0, i, k = 0, h, j, count, count2;
char input, str[100], getridof, add, character;
这是我在这种情况下所拥有的。
printf("Write a string not more then 50 chars:\n");
getchar();
i = 0;
j = 0;
count = 0;
int counts[50] = { 0 };
gets(str);
str[j] = str[i];
while (str[i] != '\0') {
if (str[i] >= 97 && str[i] <= 122) {
counts[str[i] - 97]++;
}
i++;
count++;
}
for (i = 0; i < 50; i++) {
if (counts[i] != 0) {
printf("%c: %d\n", i + 97, counts[i]);
}
}
while (str[j] != '\0') {
if (((str[j] >= 32 && str[j] <=96)) || ((str[j] >=123 && str[j] <= 126))) {
counts[str[j] - 32]++;
}
j++;
}
for (j = 0; j < 50; j++) {
if (counts[j] != 0 ) {
//if((j) < 127)
printf("%c: %d\n", j + 32, counts[j]);
}
}
printf("Total amount of char: %d\n", count);
str[i] = '\0';
system("pause");
system("cls");
这是一项学校作业,所以如果您不想说出直接代码,我理解,但我会非常感谢您提供一些提示,为我指明正确的方向。
【问题讨论】:
-
不要使用
gets().stackoverflow.com/questions/1694036/… -
您的
counts数组不够大,无法容纳您尝试在j的循环中存储的值的数量。数组中只有50整数槽,但您的索引远远超出此范围(96-32=64)。您也不会在打印它和尝试再次使用它之间重新归零您的数组。我假设您确实想这样做。 -
使用地图可以实现更简洁的实现。请查看地图文档。
-
BTW
str[i] = '\0';写入越界。