题目:
题目描述
计算字符串最后一个单词的长度,单词以空格隔开。
输入描述:
一行字符串,非空,长度小于5000。
输出描述:
整数N,最后一个单词的长度。
示例1
输入
hello world
输出
5
分析:从后往前找空格,然后根据字符串长度和这个空格下标,计算最后一个单词长度,注意find找不到返回string::npos
#include <iostream>
#include <string>
using namespace std;
int lastwd_len(string& s)
{
int pos=s.rfind(' ');//从后往前找空格
if(pos!=string::npos)
return s.size()-pos-1;
else
return s.size();
}
int main()
{
string str;
while(getline(cin, str))
{
cout<<lastwd_len(str)<<endl;
}
return 0;
}