The length of the last word of the HJ1 string

Calculate the length of the last word of the string, the words are separated by spaces, and the length of the string is less than 5000. (Note: the end of the string does not end with a space)

#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;
}

Guess you like

Origin blog.csdn.net/weixin_42836316/article/details/123264392