我正在尝试创建一个返回字符串中最后一个单词的方法但是我在编写它时遇到了一些麻烦。
我试图通过查找字符串中的最后一个空格并使用子字符串来查找单词来实现。这是我到目前为止:
String strSpace=" ";
int Temp; //the index of the last space
for(int i=str.length()-1; i>0; i--){
if(strSpace.indexOf(str.charAt(i))>=0){
//some code in between that I not sure how to write
}
}
}
我刚刚开始使用Java,所以我不知道该语言的许多复杂部分。如果有人能帮我找到解决这个问题的简单方法,我将不胜感激。谢谢!
String#lastIndexOf
和String#substring
是你的朋友。
Java中的char
s可以直接转换为int
s,我们将用它来查找最后一个空格。然后我们将从那里简单地子串。
String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(phrase.lastIndexOf(' ')));
这也会打印空间字符本身。为了摆脱这种情况,我们只需将索引的索引增加一。
String phrase = "The last word of this sentence is stackoverflow";
System.out.println(phrase.substring(1 + phrase.lastIndexOf(' ')));
如果你不想使用String#lastIndexOf
,你可以遍历字符串并在每个空格中对其进行子串,直到你没有任何左边。
String phrase = "The last word of this sentence is stackoverflow";
String subPhrase = phrase;
while(true) {
String temp = subPhrase.substring(1 + subPhrase.indexOf(" "));
if(temp.equals(subPhrase)) {
break;
} else {
subPhrase = temp;
}
}
System.out.println(subPhrase);
String str = "Code Wines";
String lastWord = str.substring(str.lastIndexOf(" ")+1);
System.out.print(lastWord);
输出:
Wines
你可以这样做:
String[] words = originalStr.split(" "); // uses an array
String lastWord = words[words.length - 1];
你已经说完了。
您将在每个空间拆分原始字符串,并使用String#split
方法将子字符串存储在数组中。
一旦有了数组,就可以通过获取最后一个数组索引的值来检索最后一个元素(通过获取数组长度并减去1来找到,因为数组索引从0开始)。
你可以使用:(如果你不熟悉数组或不寻常的方法)
public static String lastWord(String a) // only use static if it's in the
main class
{
String lastWord = "";
// below is a new String which is the String without spaces at the ends
String x = a.trim();
for (int i=0; i< x.length(); i++)
{
if (x.charAt(i)==' ')
lastWord = x.substring(i);
}
return lastWord;
}
你只需要在第一次找到空白字符串停止遍历工作时从尾部遍历输入字符串并返回word.a简单代码如下:
public static String lastWord(String inputs) {
boolean beforWords = false;
StringBuilder sb = new StringBuilder();
for (int i = inputs.length() - 1; i >= 0; i--) {
if (inputs.charAt(i) != ' ') {
sb.append(inputs.charAt(i));
beforWords = true;
} else if (beforWords){
break;
}
}
return sb.reverse().toString();
}
你可以尝试:
System.out.println("Last word of the sentence is : " + string.substring (string.lastIndexOf (' '), string.length()));