Length of Last Word - CPP Solution

1. Introduction

This blog post focuses on a straightforward yet interesting string manipulation problem in C++: finding the length of the last word in a given string. This problem tests your ability to parse strings and handle edge cases effectively.


Given a string s that consists of words and spaces, the task is to return the length of the last word in the string. A word is defined as a maximal substring consisting of non-space characters only.

2. Solution Steps

1. Start by trimming any trailing spaces from the end of the string.

2. Iterate backwards through the string until the start of the string or a space is encountered.

3. Count the number of non-space characters encountered during this backward iteration.

4. The count at the end of the iteration will be the length of the last word in the string.

3. Code Program

#include <iostream>
using namespace std;

// Function to find the length of the last word in the string
int lengthOfLastWord(string s) {
    int length = 0, i = s.length() - 1;

    // Skip trailing spaces
    while (i >= 0 && s[i] == ' ') i--;

    // Count the length of the last word
    while (i >= 0 && s[i] != ' ') {
    return length;

int main() {
    string s = "Hello World";
    cout << "Length of last word: " << lengthOfLastWord(s) << endl;
    return 0;


Length of last word: 5


1. The input string "Hello World" is processed from the end.

2. Trailing spaces are skipped, if any. In this case, there are none.

3. The function then counts the characters in the last word, "World", until a space or the start of the string is encountered.

4. The count of 5 is the length of the last word, "World".

5. The function effectively handles strings with trailing spaces and returns the correct length of the last word.