Saturday, September 5, 2020

Length of Last Word

Problem: Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.

If the last word does not exist, return 0.


        public static int LengthOfLastWord(string s)

        {

            Regex regex = new Regex(@"\s+", RegexOptions.Compiled);

            string[] words = regex.Split(s.Trim());

            if (words.Length > 0)

            {

                return words[words.Length - 1].Length;

            }

            return 0;

        }

No comments:

Post a Comment