【发布时间】:2015-04-24 11:02:44
【问题描述】:
假设如果我传递一个像"I am Programmer" 这样的字符串。
如果一个字母出现过一次,它应该打印"I has occurred 1 time",否则如果一个字母在字符串中出现两次,它应该为字符串中的每个字母打印"a has occurred 2 times"、"m has occurred 3 times"等等。我搜索了一下,在某个网站上找到了。有什么办法可以重写代码,因为我不懂代码。
#include <stdio.h>
#include <string.h>
int main()
{
char string[100];
int c = 0, count[26] = {0};
printf("Enter a string\n");
gets(string);
while (string[c] != '\0')
{
/** Considering characters from 'a' to 'z' only
and ignoring others */
if (string[c] >= 'a' && string[c] <= 'z')
count[string[c]-'a']++;
c++;
}
for (c = 0; c < 26; c++)
{
/** Printing only those characters
whose count is at least 1 */
if (count[c] != 0)
printf("%c occurs %d times in the entered string.\n",c+'a',count[c]);
}
return 0;
}
【问题讨论】:
-
还有什么问题?你试过什么?
-
我在很多网站上搜索过,但我不明白这个逻辑 Mr.Cool Guy
-
int main() { char string[100]; int c = 0,计数[26] = {0}; printf("请输入一个字符串\n");获取(字符串); while (string[c] != '\0') { /** 只考虑从 'a' 到 'z' 的字符,忽略其他字符 / if (string[c] >= 'a' && string[c ] 仅打印计数至少为 1 的字符 */ if (count[c] != 0) printf("%c 出现 %d输入字符串的次数。\n",c+'a',count[c]); } 返回 0; }
-
请缩进并格式化您的代码并将其添加到您的问题中。另外,请说明它的问题。