我刚开始学习Java之后就开始学习C,这让我有些困惑。我试图编写一个程序,目的是计算以“ A”字母开头的单词的数量。问题在于它仅读取我输入的第一个单词,而忽略句子的其余部分。有人可以帮我吗?我会很感激。
#include <stdio.h>
#include <string.h>
void main() {
char sentence[200];
int i;
int counter = 0;
printf("Enter sentence: ");
scanf("%s", &sentence);
for (i = 0; sentence[i] != 0, sentence[i] != ' '; i++){
if (sentence[i] == 'A') {
counter = counter +1;
}
}
printf("No. of A in string %s > %d\n", sentence, counter);
return 0;
}
最佳答案
用strstr
扫描字符串,查找空格后以“ A”开头的单词,然后搜索字符串中的第一个单词:
...
fgets(sentence, sizeof(sentence), stdin);
int count = 0;
const char *tmp = sentence;
while(tmp = strstr(tmp, " A")) {
count++;
tmp++;
}
if (sentence[0] == 'A') count++;
...
关于c - 计算以“A”字母开头的单词数? - C,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49470849/