尝试计算字符数并改进我的代码我做了一些更改,而不是使用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;
}
答案 0 :(得分:1)
你做了两件事。 首先是主循环。
while (myString[i]!='\0'){...}
再次使用countingCharacters
。浪费了大量资源。
此外,如果您使用strlen
,请不要while (myString[i]!='\0)
。将其替换为for (i=0;i<size;i++)
。您正在投资找到size
然后不使用它。或者,不要使用strlen
,只需执行while (myString[i]!='\0')
仅供参考:您可以等效地使用'\0'
和0
(\0
的整数值为0
)。