Given a string consisting of alphabets and digits, find the frequency of each digit in the given string

狂风中的少年 提交于 2019-12-02 22:54:48

问题


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;
}

回答1:


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/




回答2:


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.



来源:https://stackoverflow.com/questions/56715043/given-a-string-consisting-of-alphabets-and-digits-find-the-frequency-of-each-di

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!