最开始,我的代码在开始输入”a “这种情况下通不过一些用例,知道最后我发现运用s = s.trim()可以解决这个问题,去除字符串开头和结尾的所有的空格。
package genius.wyx.Algorithms;
public class WYX58 {
public static int lengthOfLastWord(String s) {
s = s.trim();
if (s.length()==0) {
return 0;
}
int count = 0;
int flag = 0;
for (int i = s.length()-1; i >= 0; i--) {
String c= " ";
if (s.charAt(i) == c.charAt(0)) {
flag = 1;
return count;
}
count++;
}
if (flag==0) {
return s.length();
}
return 0;
}
public static void main(String[] args) {
String string = "a b cd ";
System.out.println(lengthOfLastWord(string));
}
}

本文介绍了一种通过使用trim()方法去除字符串首尾空白字符的方法,并提供了一个计算最后一个单词长度的Java程序实例。
1105

被折叠的 条评论
为什么被折叠?



