标题翻译
I have to calculate LENGTH OF LAST WORD in a string.Getting error
问题
我遇到了“String Index Out Of Range”的运行时错误。我需要计算字符串中最后一个单词的长度。
class Solution
{
public int lengthOfLastWord(String s)
{
if(s==null || s.isEmpty())
{
return 0;
}
int count=0;
int len=s.length();
s=s.trim();
for(int i=len-1;i>=0;i--)
{
if(s.charAt(i)==' ')
{
break;
}
count++;
}
return count;
}
}
英文翻译
I am getting runtime error "String Index Out Of Range".I have to calculate length of last word in a string.
class Solution
{
public int lengthOfLastWord(String s)
{
if(s==null || s.isEmpty())
{
return 0;
}
int count=0;
int len=s.length();
s=s.trim();
for(int i=len-1;i>=0;i--)
{
if(s.charAt(i)==' ')
{
break;
}
count++;
}
return count;
}
}
答案1
得分: 2
你计算长度,然后可能通过修剪来缩短字符串,使实际长度比 len
小。
int len = s.length();
s = s.trim();
颠倒这些操作的顺序。
英文翻译
You calculate the length and then potentially shorten the string by trimming it, making the actual length shorter than len
.
int len = s.length();
s = s.trim();
Reverse the order of those operations.
专注分享java语言的经验与见解,让所有开发者获益!
评论