在C中使用for循环对字符串中的每个字符进行计数

ttp71kqs  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(58)

我试图计算一个字符在一个字符串中出现的次数。我想对每个字符用一个for循环来计数,这个循环有另一个循环来遍历字符串的每个字符。我不知道它有什么问题,或者是否有可能这样做。我已经看到了其他的方法可以做到这一点,但我想知道如果我接近实现它或我的代码是完全错误的。

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

int main()
{
    char A[100], ch;
    int cnt[100]={};
    gets(A);
    int x = strlen(A)-1;
    int i=0;

    for(ch='a';ch<='z';ch++)
    {
        for(i = 0; i <= x; i++)
        {
            if(A[i]==ch)
                cnt[i]++;
        }
        printf("%c is %d times in string\n", ch, cnt[i]);
    }
    return 0;
}
jc3wubiy

jc3wubiy1#

给你如果你有类似的问题,你可以问任何问题。

#include <stdio.h>

int count(char *p, char t) // Function to count occurence //
{
    int i=0;
    
    while(p[0]!= '\0')
    {
        if(p[0]==t)
        {
            i++;
        }
        
        p++;
    }
    
    return i;
}

int main()
{
    char s[1000],c;
    printf("Enter the string: ");
    scanf("%s",s);
    
    
    printf("Enter the character: ");
    scanf("  %c",&c);
    
    int j = count(s,c); // Function call //
    
    printf("The occurence of %c in string is %d",c,j);

    return 0;
}

相关问题