题解 | #字符串最后一个单词的长度#
字符串最后一个单词的长度
https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da
#牛客OJ##华为笔试#不愧是最难的C,光是输入就可以深入研究了#include <stdio.h> #include <string.h> #include <malloc.h> const int INPUT_MAX_LEN = 5000; int main() { // 创建长度为INPUT_MAX_LEN的字符数组 char* str = (char*)malloc(sizeof(char)*INPUT_MAX_LEN); // 获取1行输入,stdin声明在stdio.h中,表示从键盘标准输入 while (fgets(str,INPUT_MAX_LEN,stdin)) { int len = 0; int lastWordLen = 0; // 换行符'\n'替换成'\0' char* p = strchr(str,'\n'); if(p!=NULL) { *p = '\0'; } len = (int) strlen(str); // 没空格的情况 if(strchr(str,' ') == NULL) { printf("%d\n", len); continue; } // 有的情况 for (int i = len-1; i > 0; i--) { if(str[i] == ' ') { break; } lastWordLen++; } printf("%d\n", lastWordLen); } }