Given a string consisting of alphabets and digits,

2020-05-09 18:40发布

Please tell me whats wrong in code the output is 00000000.
I know there is some mistake but cant find it.

#include <stdio.h>
#include <string.h>

int main()
{
     int c=0;
     char s[100];
     fgets(s, 100, stdin);
     printf("%s", s);
     for(int i=0;i<=9;i++)
     {
         for(int j=0;j<strlen(s);j++)
         {
             if(s[j]==i){
                 c++;
            }           
         }
         printf("%d", c);
     }

    return 0;
}

2条回答
神经病院院长
2楼-- · 2020-05-09 19:17

Firstly, you are comparing a character with a int. Have a look at Char to int conversion in C for a solution.

Then, I would remember you that "0" is index 48 in ASCII table, not 0 : http://www.asciitable.com/

查看更多
Viruses.
3楼-- · 2020-05-09 19:32

The key problem is s[j]==i. That compares a char of the string to the values 0 to 9 ratter than to char '0' to '9'.

Another is the c is not reset to zero each loop.


Instead of looping 10 times, test if the char is a digit.

Instead of calling j<strlen(s) repeatedly, just test if s[j] == 0

 size_t digit_frequency[10] = {0};

 for (size_t i=0; s[i]; i++) {
   if (isdigit((unsigned char) s[i])) {
   // or  if (s[i] >= '0' && s[i] <= '9') {
     digit_frequency[s[i] - '0']++;
   }
 }

 for (size_t i=0; i<10; i++) {
   pritnf("%zu\n", s[i]);
 }

Code uses size_t rather than int as a string's length is limited to size_t - which may exceed int in extreme cases. Either work OK work size 100.

isdigit() declared in <ctype.h>

(unsigned char) used as isdigit() expect a value in the (unsigned char) and EOF and a char may be negative.

Various style choices - all function the same.

for (size_t i=0; s[i]; i++) {
for (size_t i=0; s[i] != '\0'; i++) {
for (size_t i=0; s[i] != 0; i++) {

"Given a string consisting of alphabets and digits" is a minor contraction. In C, a string includes the final null character: "A string is a contiguous sequence of characters terminated by and including the first null character" C11 §7.1.1 1. Yet folks often speak colloquially as is the null character was not part of the string.

查看更多
登录 后发表回答