0

我必须找到字符串中的最后一个单词,并且不明白为什么我的代码不起作用。这就是我所拥有的:

int i, length;
String j, lastWord;
String word = "We the people of the United States in order to form a more perfect union";    
length = word.length();    



for (i = length - 1; i > 0; i--)
{
  j = word.substring(i, i + 1);
  if (j.equals(" ") == true);
  {
    lastWord = word.substring(i);
    System.out.println("Last word: " + lastWord);
    i = -1; //to stop the loop
  }
}

但是,当我运行它时,它会打印最后一个字母。我知道我可以使用

字符串 lastWord = word.substring(word.lastIndexOf(" ") + 1)

但我很确定我的老师不希望我这样做。有什么帮助吗?

4

6 回答 6

4

您需要删除;之后if才能使其工作:

if (j.equals(" ")) // <== No semicolon, and no == true
{
    lastWord = word.substring(i);
    System.out.println("Last word: " + lastWord);
    i = -1; //to stop the loop
}

您也不需要== true控制语句中的布尔值。

最后,制作单字符子字符串比使用单字符更昂贵。考虑charAt(i)改用:

if (word.charAt(i) == ' ') // Single quotes mean one character
{
    lastWord = word.substring(i+1);
    System.out.println("Last word: " + lastWord);
    break; // there is a better way to stop the loop
}
于 2012-12-06T02:39:01.093 回答
3

您已终止该if声明。它应该是,

if(j.equals(" "))
{
 ...
}
于 2012-12-06T02:39:03.153 回答
1

把它;if (j.equals(" ") == true);外面拿出来。

您的代码重做更清洁:

String word = "We the people of the United States in order to form a more perfect union";
for (int i = word.length() - 1; i > 0; i--)
  if (word.charAt(i - 1) == ' ') {
    System.out.println("Last word: " + word.substring(i));
    break; // To stop the loop
  }

最小迭代。

于 2012-12-06T02:39:41.827 回答
1

Convert the string to char array and look for space from the end of array. Don't forget to remove white spaces from the end using trim() as they could be counted as separate words.

s = s.trim();
char[] c = s.toCharArray();
for(int i=0; i<c.length; i++)
{
    if(c[c.length-1-i]==' ')
    {
        return s.substring(c.length-1-i);
    }
}
return s;

This also covers the null string case.

Another alternative using split.

s = s.trim();
String[] strs = new s.split(' ');
return str[str.length-1];
于 2019-08-29T23:09:56.980 回答
0

“if”语句后面的分号表示“什么也不做”。此外,“== true”是多余的。最后,您不想包含刚刚找到的空间。尝试这个:

for (i = length - 1; i > 0; i--)
  {
  j = word.substring(i, i + 1);
  if (j.equals(" "))
  {
    lastWord = word.substring(i + 1);
    System.out.println("Last word: " + lastWord);
    i = -1; //to stop the loop
  }
}
于 2012-12-06T02:43:12.790 回答
0

在http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split%28java.lang.String%29有一种拆分字符串的方法

Splits this string around matches of the given regular expression.

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array. 

一个好的、快速和简单的方法是:

word = word.split(" ")[word.length-1];

split()返回一个基于 " " 的子字符串数组。由于数组从 0 开始,所以它的最后一个元素是数组的长度 - 1。

于 2012-12-06T05:33:33.060 回答