题解 | #字符串最后一个单词的长度#
字符串最后一个单词的长度
https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da
#include <stdio.h>
#include <string.h>
//计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。
//实现
int iswordseparator(char c) {
//暂定单词分割符为空白字符
if (c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v') {
return 1;
}
return 0;
}
int getlengthoflastword(char* str) {
int i = 0, length = 0;
length = strlen(str);
//右边空白无视
while ((length >= 1) && iswordseparator(str[length - 1]) == 1) {
length--;
}
//左边是空白结束
while ((length >= 1) && iswordseparator(str[length - 1]) != 1) {
i++;
length--;
}
return i;
}
//测试
char buf[5000];
int main() {
int length = 0;
memset(buf, 0, sizeof(buf));
while (fgets(buf, sizeof(buf), stdin) != NULL) {
length = getlengthoflastword(buf);
printf("%d\n", length);
memset(buf, 0, sizeof(buf));
}
return 0;
}
1,读取用fgets,不使用scanf。
2,输出用printf
3,抽取iswordseparator函数,用来区分单词和非单词部分
4,抽取getlengthoflastworld函数,完成计算最后一个单词长度的功能
5,测试用例支持多次输入。读取失败时退出。
查看28道真题和解析