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.
文章意思很明确,就是给定一个字符串让你输出最后一个String的长度,其中用空格分开。
想到空格分割,第一反应时采用split,其次为防止其有多个空格,因此使用正则表达式
的+号处理(+号代表1个或多个),直接上代码:
public int lengthOfLastWord(String s) {
String [] words=s.split(" +");
if(words==null) return 0;
int len = words.length;
if(len==0) return 0;
return words[len-1].length();
}
不知道为什么,如果字符串首尾都有空格,在调试时每次都会将串首的空字符作为String数组的一部
分,而尾部不会有,因此每次首字母都会多出一个,这道题要求得是最后一个,如果要完整使用这
个String数组,还需要将第一个空字符去掉。