Title description
Calculate the length of the last word in the string, separated by spaces.
Enter description:
A line of strings, not empty, and less than 5000 in length.
Output description:
Integer N, the length of the last word.
Example 1:
Type
hello world
Output
5
Ideas:
-
There is a space between each word in the string
-
Use rfind ('') to query the subscript of the last space
-
Then calculate the length of the string without \ 0
-
The length of the string minus the subscript of the last space can get the length of the last word
Code example:
#include <iostream>
#include <string>
using namespace std;
int main(){
string str;
getline(cin, str);
int len = str.rfind(' ');
if(len == 0){
cout << str.size() - 1 << endl;
}
else
cout << str.size() - len - 1 << endl;
return 0;
}