DEV Community

Cover image for C# LeetCode 58: Length of Last Word
Grant Riordan
Grant Riordan

Posted on

C# LeetCode 58: Length of Last Word

Problem

Given a string s consisting of words and spaces, return the length of the last word in the string.

A word is a maximal substring consisting of non-space characters only.

Code

public int LengthOfLastWord(string s) {

        var words = s.Split(" ", StringSplitOptions.RemoveEmptyEntries).ToArray();
        return words[^1].Length;
    }
Enter fullscreen mode Exit fullscreen mode

Approach

The aim is the remove all the empty spaces so that we just have the words, we then get the last word.

This can easily be done using the Split() method, which takes the character to split on (in our case space) and then we can pass an extra argument of RemoveEmptyEntries will after splitting will remove all our spaces.

Then using the [^1] syntax we can obtain the last index from the end, to return the final word.


As always to learn more, or see future articles drop me a follow on DevTo or my twitter

Top comments (0)