这题乍一看挺好做的,但是还要考虑的详细一点,坑挺多的,尤其是空格的位置要考虑好。
public class LengthofLastWord {
public static void main(String[] args) {
String s="";
LengthofLastWord lastWord=new LengthofLastWord();
System.out.println(lastWord.LastWord(s));
}
public int LastWord(String s) {
int n=s.length();
int t=0;
while(n>0&&s.charAt(n-1)==' ')
{
n-=1;
}
for(int i=n-1;i>=0;i--)
{
if(s.charAt(i)==' ')
{
break;
}
else
{
t++;
}
}
return t;
}
}
本文介绍了一种计算字符串中最后一个单词长度的方法,通过去除末尾空格并逆向遍历字符,直到遇到空格为止,以此来确定最后一个单词的长度。

490

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



