2

I'm trying to count the number of each character in the string with using a searching function and adding every time it appears.

Here's my program so far

            #include<stdio.h>


            int countCharactersCaseSensitive(char *inStr, char);

            int main()
            {
                char ascii[52];
                int capital = 65;
                int i;
                for (i = 0; i <26; i++)
                {
                    ascii[i] = capital;
                    capital++;
                }
                int lower = 97;
                for (i=26; i< 52; i++)
                {
                    ascii[i] = lower;
                    lower++;
                }


                char *str = "Programming Assignment";
                int count[52];
                for (i=0;i<52;i++)
                {
                    char check = ascii[i];
                    count[i] = countCharactersCaseSensitive(str,check);

                }

                    for(i=0;i<52;i++)
                {
                    printf("%c%10d\n",ascii[i],count[i]);
                }

            }


            int countCharactersCaseSensitive(char *inStr, char check)
            {
                int i;
                int count = 0;
                int length = strlen(inStr);
                for (i=0;i<length;i++)
                {
                    if(check == *inStr)
                    {
                        inStr++;
                        count++;
                    }
                }
                return count;
            }

But it only checks for P, how do i fix this to check the other characters in the string?

4

3 回答 3

3
for (i=0;i<length;i++)
{
    if(check == *inStr)
    {
        inStr++;
        count++;
    }
}

当您找到检查字符时,您只会推进 inStr 。您需要在每次迭代中推进它。

for (i = 0; i < length; i++, inStr++)
{
    if (check == *inStr)
    {
        count++;
    }
}
于 2013-11-12T21:40:55.443 回答
0

因为这

if(check == *inStr) 
{
    inStr++;
    count++;
}

仅当指针匹配时才增加指针,并且由于第一个字符是 aP并且该字符仅出现一次,因此您只能得到 1P

您需要在 if 语句之外递增。

要么做

if(check == *inStr) 
{
    count++;
}
inStr++;

或者

if(check == inStr[i]) 
{
    count++;
}
于 2013-11-12T21:40:43.180 回答
0

您实际上并没有在您尝试搜索的字符串中前进。我建议以下两种更改中的任何一种:

int length = strlen(inStr);
for (i=0;i<length;i++)
{
     if(check == inStr[i])
     {
         count++;
     }
}

或者

char * strPtr;

for (strPtr = inStr; *strPtr; strPtr++)
{
     if(check == *strPtr)
     {
         count++;
     }
}
于 2013-11-12T21:45:04.993 回答