HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Length of last word

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
lengthlastword

Problem

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

For example:

s               result 

"Hello World"    5
"a "             1
" a "            1  
"  ba "          2  
"ba    "         2


The following is my code:

int lengthOfLastWord(const char* s)
{                   
    const char* end=s;
    while (*end != '\0')
    {
        ++end;
    }
    --end;

    while ((end >= s) && (*end == ' '))
    {
        --end;
    }

    const char* start = end;
    while ((start >= s) && (*start != ' '))
    {
        --start;
    }

    return end-start;
}

Solution

This is just the @palacsint solution extended to ignore trailing spaces.

int lengthOfLastWord2(const char* input)
{
    int result = 0;
    int last_result = 0;

    while (*input != '\0') {
        if (*input != ' ') {
            result++;
        } else if (result) {
            last_result = result;
            result = 0;
        }
        input++;
    }
    return result ? result : last_result;
}

Code Snippets

int lengthOfLastWord2(const char* input)
{
    int result = 0;
    int last_result = 0;

    while (*input != '\0') {
        if (*input != ' ') {
            result++;
        } else if (result) {
            last_result = result;
            result = 0;
        }
        input++;
    }
    return result ? result : last_result;
}

Context

StackExchange Code Review Q#23641, answer score: 4

Revisions (0)

No revisions yet.