尝试对字符进行计数并改进我的代码我做了一些更改,而不是使用while循环,例如。好奇,如果任何人有任何建议,我可以改善我的代码,使其更专业,更便宜?使用函数计算字符(频率)
#include <stdio.h>
int countingCharacters(char *message, int size, char charsToBeCounted);
int main()
{
char myString[] = "Hello World!";
int size = strlen(myString);
char charToBeCounted = 'a';
int i = 0;
int counter = 0;
while (myString[i] != '\0')
{
if (myString[i] == charToBeCounted)
{
counter++;
}
++i;
}
for (int i = 'a'; i <= 'z'; i++)
{
printf("%c: %d\n", charToBeCounted, countingCharacters(myString, size, charToBeCounted));
charToBeCounted++;
}
getchar();
return 0;
}
int countingCharacters(char *message, int size, char charsToBeCounted)
{
int counter = 0;
for (int i = 0; i < size; i++)
{
if (message[i] == charsToBeCounted)
counter++;
}
return counter;
}
为什么'while'循环在那里?你没有在任何地方使用“counter”。 –
“建议如何改进我的代码,使其更专业,更便宜?” - >考虑https://codereview.stackexchange.com - 一个更好的网站选择。 (这假定它的功能正确) – chux
我看到'countingCharacters()'至少有4个改进,在[codereview](https://codereview.stackexchange.com/)上发布工作代码。 – chux