【发布时间】:2017-10-01 16:59:29
【问题描述】:
例如,为了计算字符数并改进我的代码,我做了一些更改,而不是使用 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。 -
"建议我如何改进我的代码,使其更专业、更便宜?" --> 考虑codereview.stackexchange.com - 一个更好的站点选择。 (这假设它正常工作)
-
我看到
countingCharacters()至少有 4 项改进,在 codereview 发布工作代码。 -
真正改进您的代码:第 1 步:清楚地将 代码 与 测试代码 分开。您是否只关心
countingCharacters()或char myString[] = "Hello World!";之后的所有内容或什么?
标签: c arrays string function char