Length of Last Word - C Solution

1. Introduction

This blog post discusses a common string processing problem in C programming: determining the length of the last word in a given string. The challenge lies in efficiently navigating through the characters, handling spaces, and identifying words. This problem is a fundamental exercise in string manipulation.

Problem

Given a string 's' that consists of words separated by spaces, the objective is to return the length of the last word in the string. A word is defined as a maximal substring consisting exclusively of non-space characters.

2. Solution Steps

1. Start from the end of the string and move backwards.

2. Skip any trailing spaces at the end of the string.

3. Count the number of non-space characters until a space or the start of the string is encountered.

4. Return the count, which represents the length of the last word.

3. Code Program

#include <stdio.h>
#include <string.h>

// Function to find the length of the last word in the string
int lengthOfLastWord(char *s) {
    int length = strlen(s); // Get the length of the string
    int wordLength = 0; // Variable to store the length of the last word

    // Loop to skip trailing spaces
    while (length > 0 && s[length - 1] == ' ') {
        length--; // Decrement the length to ignore the space
    }

    // Loop to count the length of the last word
    while (length > 0 && s[length - 1] != ' ') {
        wordLength++; // Increment the word length
        length--; // Decrement the length
    }

    return wordLength; // Return the length of the last word
}

int main() {
    char s[] = "Hello World"; // Example string
    int result = lengthOfLastWord(s); // Call the function
    printf("Output: %d\n", result); // Print the result

    return 0;
}

Output:

5

Explanation:

The program calculates the length of the last word in the string "Hello World". It starts from the end of the string, skipping any trailing spaces. Then, it counts the number of characters until a space is found, which denotes the end of the last word. In this case, the last word is "World", which has a length of 5. Therefore, the output is 5. The function handles various cases, including trailing spaces and a single word, making it robust for different inputs.


Comments