#include <stdio.h>
#include<string.h>
int countlastword(char *s){
int i=strlen(s)-1;
int count=0;
while(i>=0&&s[i]==' '){
i--;
}//找到末尾单词
while(i>=0&&s[i]!=' '){
i--;
count++;
}//计算长度
return count;
}
int main() {
char s[5000];
char c;
int i=0;
while ((c = getchar()) != '\n' &&c!=EOF&&i<sizeof(s)-1)
{s[i]=c;
i++;} //使用getchar逐个接收字符
s[i] = '\0';
printf("%d",countlastword(s));
return 0;
}
子函数中,先倒着找到最后一个单词,然后再计数。注意strlen和sizeof的区别。
主函数中,注意如何接收字符串,不可以使用scanf,因为遇到空格就会结束。可以使用getchar逐个接收,也可以使用fgets函数。 \n换行符,\0空字符、EOF结束标识符。