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

标签 c string

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

例如,如果我输入 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;
}

最佳答案

最好将您正在做的事情分成两个函数,其中一个函数将计算每个字母出现的次数。

#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。我将其作为练习留给读者。

关于计算字符串中有多少个字母重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53253339/

相关文章:

python - 在数据框中附加带有字符串值的列

javascript - 使用正则表达式将字符串拆分为 "\\"和 "."

c - 字符串函数返回段错误

c - C中用0填充字符

c++ - 将字符串转换为数学评估

c - 对 `polyndrom' 、 `uppercase' 和 `lowercase' 的 undefined reference

C代码: how to detect duplicate function declarations

c - 是否有与 Perl 的 Carp 模块等效的 C 语言?

android - 优化我的内部循环(ARM,android ndk)

c - 12 小时制 AM/PM 格式到军用(24 小时制)时间