2017-05-03 102 views
0

尝试对字符进行计数并改进我的代码我做了一些更改,而不是使用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

为什么'while'循环在那里?你没有在任何地方使用“counter”。 –

+0

“建议如何改进我的代码,使其更专业,更便宜?” - >考虑https://codereview.stackexchange.com - 一个更好的网站选择。 (这假定它的功能正确) – chux

+0

我看到'countingCharacters()'至少有4个改进,在[codereview](https://codereview.stackexchange.com/)上发布工作代码。 – chux

回答

1

你正在做整件事两次。首先在主循环中使用 。

while (myString[i]!='\0'){...} 

而且随着countingCharacters的一次。浪费大量资源。

此外,如果您使用strlen不要做while (myString[i]!='\0)。将其替换为for (i=0;i<size;i++)。您正在投资寻找size,然后不使用它。或者不使用strlen,只是做while (myString[i]!='\0')

FYI:您可以使用'\0'0相同(的\0整数值是0)。

+1

'\ 0'表示更好的意思。 –

+0

没错。这只是'0'在手指上更容易。 :P –

+0

'while(myString [i]!='\ 0')'在代码审查和维护人员的眼中很容易,如果您同意[this](https://www.ncbi。 nlm.nih.gov/pmc/articles/PMC3610582/)。 'while(myString [i])'是简单的选择。 – chux