最后一个单词的长度

给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。

如果不存在最后一个单词,请返回 0 。

说明:一个单词是指由字母组成,但不包含任何空格的字符串。

示例:
输入: "Hello World"
输出: 5


public int LengthOfLastWord(string s) {

    if(s == null || s.Length == 0) return 0;

    //去除两边空格
    s = s.Trim();
    //从后面遍历到空格
    int length = 0;
    int index = s.Length - 1;
    while(index >= 0 && s[index] != ' ')
    {
        length++;
        index--;
    }

    return length;
}

首页 我的博客
粤ICP备17103704号