3 回答

TA貢獻(xiàn)1863條經(jīng)驗(yàn) 獲得超2個贊
你可以這樣做:
String[] words = originalStr.split(" "); // uses an array
String lastWord = words[words.length - 1];
你有你的最后一句話。
您在每個空格處拆分原始字符串,并使用該方法將子字符串存儲在數(shù)組中String#split。
獲得數(shù)組后,您將通過獲取最后一個數(shù)組索引處的值來檢索最后一個元素(通過獲取數(shù)組長度并減去 1,因?yàn)閿?shù)組索引從 0 開始)。

TA貢獻(xiàn)1843條經(jīng)驗(yàn) 獲得超7個贊
String str = "Code Wines";
String lastWord = str.substring(str.lastIndexOf(" ")+1);
System.out.print(lastWord);
輸出:
Wines

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個贊
String#lastIndexOf并且String#substring是你這里的朋友。
charJava 中的 s 可以直接轉(zhuǎn)換為ints,我們將使用它來查找最后一個空格。然后我們將簡單地從那里子串。
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,則可以遍歷字符串并在每個空格處對其進(jìn)行子字符串處理,直到您沒有任何剩余為止。
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);
添加回答
舉報