第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何找到字符串中的最后一個單詞

如何找到字符串中的最后一個單詞

達(dá)令說 2022-06-23 16:33:29
我正在嘗試創(chuàng)建一個返回字符串中最后一個單詞的方法,但我在編寫它時遇到了一些麻煩。我試圖通過查找字符串中的最后一個空格并使用子字符串來查找單詞來做到這一點(diǎn)。這是我到目前為止所擁有的:    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,所以我不知道該語言的許多復(fù)雜部分。如果有人可以幫助我找到解決此問題的簡單方法,將不勝感激。謝謝!
查看完整描述

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 開始)。


查看完整回答
反對 回復(fù) 2022-06-23
?
藍(lán)山帝景

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


查看完整回答
反對 回復(fù) 2022-06-23
?
慕沐林林

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);


查看完整回答
反對 回復(fù) 2022-06-23
  • 3 回答
  • 0 關(guān)注
  • 183 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號