Length of Last Word - C Solution

1. Introduction

In this post, we'll explore a common string manipulation problem in C programming - finding the length of the last word in a given string. This problem is a good exercise in understanding how to work with strings and substrings in C, as well as handling edge cases like trailing spaces.

Problem

Given a string s consisting of words separated by 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 from the end of the string and move backwards.

2. Skip any trailing spaces.

3. Count the length of the last word until a space or the beginning of the string is encountered.

4. Return 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 a string
int lengthOfLastWord(char * s) {
    int length = 0;
    int i = strlen(s) - 1;

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

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

    return length;
}

// Main function to test the lengthOfLastWord function
int main() {
    char s1[] = "Hello World";
    printf("Length of Last Word in 'Hello World': %d\n", lengthOfLastWord(s1));

    char s2[] = "   fly me   to   the moon  ";
    printf("Length of Last Word in '   fly me   to   the moon  ': %d\n", lengthOfLastWord(s2));

    char s3[] = "luffy is still joyboy";
    printf("Length of Last Word in 'luffy is still joyboy': %d\n", lengthOfLastWord(s3));

    return 0;
}

Output:

Length of Last Word in 'Hello World': 5
Length of Last Word in '   fly me   to   the moon  ': 4
Length of Last Word in 'luffy is still joyboy': 6

Explanation:

1. int length = 0; - Initialize the length of the last word.

2. int i = strlen(s) - 1; - Start from the end of the string.

3. while (i >= 0 && s[i] == ' ') { i--; } - Skip trailing spaces.

4. while (i >= 0 && s[i] != ' ') { length++; i--; } - Count the length of the last word.

5. return length; - Return the length of the last word.

6. The main function tests the lengthOfLastWord function with three examples and prints the lengths of the last words.


Comments