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

计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。(注:字符串末尾不以空格为结尾)

#include <iostream>
#include <string>

using namespace std;

int main()
{
    
    
	string s;
	getline(cin,s);
	size_t pos = s.rfind(' ');	
	if (pos == string::npos)
	{
    
    
		//没有找到
		cout << s.size() << endl;
	}
    else
    {
    
    
        cout << s.size() - pos -1<< endl;
    }	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42836316/article/details/123264392