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,
Given s = "Hello World"
,
return 5
.
我是用一种分开的办法
public class Solution {
public int lengthOfLastWord(String s) {
String[] str = s.split(" ");
if(str.length == 0) return 0;
return str[str.length-1].length();
}
}
然后这是一种更简单的方法
public int lengthOfLastWord(String s) {
return s.trim().length()-s.trim().lastIndexOf(" ")-1;//trim()用来去掉字符串对象开头和结尾的空格 lastIndexOf用来返回后面指定字符串最后出现的位置
}