Calculating the length of the last word of the string, the words separated by a space. (C ++)

Enter a description:

His string, a non-empty, a length of less than 5000.

Output Description:

Integer N, the length of the last word.

Example 1

Entry

hello world

Export

5
#include<iostream>
#include<string>
using namespace std;
int main()
{
	string line;
	int len=0;
	int num=0;
	getline(cin,line);
	len=line.length()-1;
	while(len>=0)
	{
		if(line[len]==' ')
			{
				len--;
				continue;
			}
		else
			break;
	}
	while(line[len]!=' ')
			{
				len--;
				num++;
				if(len<0)
					break;
			}
	cout<<num<<endl;
	return 0;
}

 

Published 18 original articles · won praise 3 · views 20000 +

Guess you like

Origin blog.csdn.net/wangxiaolin1992/article/details/81510643