计算一个字符串中重复多少个字母

时间:2018-11-11 21:18:49

标签: c string

我的程序应首先读取输入的字符串word,然后计算重复字母的数量。

例如,如果我输入apple,则应打印1,但应打印4

我认为word[i] = word[i + 1]不是正确的计数方法吗?

#include<stdio.h>

int main() {

    int i, j, wordLength = 0, alphabeticalSort, counter = 0, swap;
    char word[51];

    scanf("%s", word);

    while (word[wordLength] != '\0'){
        wordLength++;
    }

    ...

    for (i = 0; i < wordLength; i++){
        if (word[i] = word[i + 1])
            counter++;
    }

    printf("\nNumber of repeated letters: %d", counter);

    ...

    return 0;
}

3 个答案:

答案 0 :(得分:1)

最好将正在执行的操作分为两个功能,其中一个功能将计算每个字母的出现次数。

#define LETTERS 26

/* counts number of occurrences of each lowercase letter in str. Result is placed in outCounts, 
   assuming it has room */
void countletters(char *str, int outCounts[])
{
    memset(outCounts, 0, LETTERS * sizeof (int));

    for (; *str; ++str) {
        if (isupper(*str))
            *str = tolower(str);
        if (islower(*str))
            ++outCounts[*str - 'a'];
    }
}

然后,您编写另一个函数将检查outCounts数组,该数组已修改。如果重复字母,则此数组的相应成员将大于一个。我把这留给读者练习。

答案 1 :(得分:0)

int main()
{
    char string[80];
    int c = 0, count[26] = {0}, x;

    printf("Enter a string\n");
    //gets(string); 
    scanf("%s", string); 
    while (string[c] != '\0') {

       if (string[c] >= 'a' && string[c] <= 'z') {
          x = string[c] - 'a';
          count[x]++;
       }

       c++;
    }

    for (c = 0; c < 26; c++)
       printf("%c occurs %d times in the string.\n", c + 'a', count[c]);

    return 0;
}

答案 2 :(得分:0)

您有:

for (i = 0; i < wordLength; i++){
    if (word[i] = word[i + 1])
        counter++;
}

看看循环内的“比较”;您将word[i+1]的值赋予word[i+1]。除非word[i+1]的值为0或在ASCII表中也为0的空字符,否则该条件将始终为真。

请记住:C中的相等运算符始终为==,因此将=替换为==