题解 | #字符串最后一个单词的长度#
字符串最后一个单词的长度
https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { // int a, b; // while (scanf("%d %d", &a, &b) != EOF) { // 注意 while 处理多个 case // // 64 位输出请用 printf("%lld") to // printf("%d\n", a + b); // } char str[5000] = {0}; int ch; int str_len = 0; while((ch = getc(stdin)) != EOF) { if (str_len >= 5000) { break; } if (ch == '\n') { break; } str[str_len++] = ch; } int i = str_len; while( str[--i] != ' ' && i > 0); int word_len = 0; if (i == 0) { word_len = str_len - i; } else { word_len = str_len - i-1; } printf("%d\n", word_len); return 0; }
描述
计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。(注:字符串末尾不以空格为结尾)
输入描述:
输入一行,代表要计算的字符串,非空,长度小于5000。
输出描述:
输出一个整数,表示输入字符串最后一个单词的长度。
示例1
输入:
hello nowcoder
输出:
8
说明:
最后一个单词为nowcoder,长度为8
首先是分析题目:
1.输入一行,需要实现从终端获取一行字符串的函数,不包括回车。
2.字符串长度少于5000,那么5000个字符类型的数组足够用了
3计算单词长度,该字符串可能有多个单词,可能只有一个单词。
解题:获取一行字符串的代码
char str[5000] = {0}; int ch; int str_len = 0; while((ch = getc(stdin)) != EOF) { if (ch == '\n') { break; } str[str_len++] = ch; }
获取最后一个单词在字符串中的位置,两种情况,①最后一个单词前是' ',②最后一个单词即是第一个单词
int i = str_len; while( str[--i] != ' ' && i > 0);//如果最后一个单词即是第一个单词,此时i==0,跳出循环
输出单词长度,注意两种情况的区别
int word_len = 0; if (i == 0) { word_len = str_len - i;//first } else { word_len = str_len - i-1;//first word //' '的下标是5,字符串长度是10,10-5=5,不对,要再-1 } printf("%d\n", word_len);