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

Posted on 2016-03-25 19:55  徐岩  阅读(273)  评论(1)    收藏  举报

题目: 计算字符串最后一个单词的长度,单词以空格隔开。

输入: 一行字符串。

输出: 整数N,最后一个单词的长度。

例如: hello world     输出: 5

思路: 考虑到最后一个单词中可能含有空格,例如: “Hello world#" (#表示空格)

int lenOfLastWord(const string &s)
{
    if(s == "") return 0;
    istringstream is(s);
    string last;
    while(is >> last);
    return last.size();
}