我的程序应该首先读取输入的字符串单词
,然后计算重复字母的数量。
例如,如果我输入 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/