c - 我有一串字母和数字,我必须找到其中每个数字从 0 到 9 的频率

标签 c

我有一串字母和数字,我必须找到其中从 0 到 9 的每个数字出现的频率。

我采用了嵌套的 for 循环,第一个用于数字,第二个用于字符串。然后使用 if.. else.. 来比较两者

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

int main() {
int i,j,count=0;
char s[1000];
scanf("%s",s);
for(i=0;i<=9;i++)
{
    for(j=0;j<strlen(s);j++)
    {
        if(i==s[j])
        {
            count=count+1;
        }    
    }
    printf("%d ",count);
    count=0;
    }  
return 0;
}

如果输入为“abdf2343”,则输出必须为 0 0 1 2 1 0 0 0 0 0。 但我的输出是 0 0 0 0 0 0 0 0 0 0

最佳答案

请尝试此代码:

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

int main() { 
    char s[1000];
    scanf("%s",&s);
    char str[10]={'0','1','2','3','4','5','6','7','8','9'};   
    int count=0;
    for(int i=0;i<=9;i++)
    {
        for(int j=0;j<strlen(s);j++)
        {
            if(str[i]==s[j])
            {
                count=count+1;
            }
        }
        printf("%d ",count);
        count=0;
    }
    return 0;
}

关于c - 我有一串字母和数字,我必须找到其中每个数字从 0 到 9 的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57320922/

相关文章:

c - 与 HTTP 1.0 相比,HTTP 1.1 延迟 20 秒

用于查找押韵的 C 程序

c - 整数类型指针的大小和 int* 的大小

android - pthread_t 在 android 和 linux 中

c - 将指针传递给具有指向 const 指针的形式参数的函数时的未定义行为?

c - 在C中读取和写入unicode字符到文件

c - C 中的递归不返回字符串值

c - 密码功能不起作用

c - 如何解释数据类型大小及其对齐方式?

c - 在 printf 函数内扩展动态宏