题解 | 字符串最后一个单词的长度

#include <iostream>
using namespace std;

int main() {
    string sentence;
    while (getline(cin, sentence)) { // 注意 while 处理多个 case

        int word_len = 0;
        for (int i = sentence.size() - 1; i >= 0; i --) {
		  // 倒着计算单词的长度
            if (sentence[i] != ' ') { 
                word_len ++;
            } else if (sentence[i] == ' ') { //第一次出现空格 退出
                break;
            }
        }
        cout << word_len << endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务