简体   繁体   English

使用for循环获取字符串中的最后一个单词?

[英]Get the last word in a string using a for loop?

I have to find the last word in a string and can't understand why my code isn't working. 我必须在字符串中找到最后一个单词,但无法理解为什么我的代码无法正常工作。 This is what I have: 这就是我所拥有的:

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
  }
}

However, when I run it, it prints the last letter. 但是,当我运行它时,它会打印最后一个字母。 I know I could use 我知道我可以用

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

But I'm pretty sure my teacher doesn't want me to do it this way. 但是我很确定我的老师不希望我这样做。 Any help? 有什么帮助吗?

You need to remove the ; 您需要删除; after the if to make it work: 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
}

You do not need == true for booleans inside control statements, either. 您也不需要控制语句内的布尔值== true

Finally, making single-character substrings is more expensive than using single characters. 最后,制作单个字符的子字符串比使用单个字符更昂贵。 Consider using charAt(i) instead: 考虑改用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
}

You've terminated the if statement. 您已经终止了if语句。 It should be, 它应该是,

if(j.equals(" "))
{
 ...
}

Just take that ; 只是接受; from if (j.equals(" ") == true); if (j.equals(" ") == true); out. 出来。

Your code remade cleaner: 您的代码经过了重新整洁:

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
  }

Minimum iterations. 最小迭代次数。

Convert the string to char array and look for space from the end of array. 将字符串转换为char数组,然后从数组末尾查找空格。 Don't forget to remove white spaces from the end using trim() as they could be counted as separate words. 不要忘记使用trim()从末尾删除空格,因为它们可以算作单独的单词。

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. 使用split的另一种选择。

s = s.trim();
String[] strs = new s.split(' ');
return str[str.length-1];

The semicolon after your "if" statement means "do nothing." “ if”语句后的分号表示“不执行任何操作”。 Also, the "== true" is redundant. 同样,“ == true”是多余的。 Lastly, you don't want to include the space you just found. 最后,您不想包括刚刚找到的空间。 Try this: 尝试这个:

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
  }
}

There's a method for strings to split up at http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split%28java.lang.String%29 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. 

A good, fast and easier way would be: 一个好的,快速和容易的方法是:

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

split() returns an array of substrings based on " ". split()返回基于“”的子字符串数组。 Since an array starts with 0, its last element is the length of the array - 1. 由于数组以0开头,因此它的最后一个元素是数组的长度-1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM