[Daily question] 17: The length of the last word in the string

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:

  1. There is a space between each word in the string

  2. Use rfind ('') to query the subscript of the last space

  3. Then calculate the length of the string without \ 0

  4. 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;
}

Insert picture description here

Published 152 original articles · praised 45 · 10,000+ views

Guess you like

Origin blog.csdn.net/AngelDg/article/details/105041098