要求:
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.
简而言之:将字符串中的最后一个单词的长返回给main
注意:要去掉字符串首尾的空格,使用trim()方法,一开始没注意这个问题
public int lengthOfLastWord(String s) {
char[] ch = s.trim().toCharArray();
int sum = 0;
if (ch.length == 0)
return 0;
for (int i = ch.length - 1; i >= 0; i--) {
if (Character.isSpace(ch[i])) {
sum = ch.length - i - 1;
break;
}
if (i == 0)
return ch.length;
}
return sum;
}