字符串最后一个单词的长度(C++ 牛客网)

解题思路:

(1)从后往前,遇到第一个空格截止


#include <iostream>
#include <string>
#include <cctype>

using namespace std;
int len(string &s) {
    int i = s.length()-1;
    int count = 0;
    while(i>=0 && !isspace(s[i])) {
        count++;
        i--;
    }
    return count;
}
int main() {
    string s;
    getline(cin,s);
    cout<<len(s);
    return 0;
}
发布了302 篇原创文章 · 获赞 277 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/105668233