簡體   English   中英

最簡單的方法來獲取除字符串中的最后一個單詞之外的每個單詞

[英]easiest way to get every word except the last word from a string

除了字符串中的最后一個單詞之外,在字符串中獲取每個單詞的最簡單方法是什么? 到目前為止,我一直在使用以下代碼來得到最后一句話:

String listOfWords = "This is a sentence";
String[] b = listOfWords.split("\\s+");
String lastWord = b[b.length - 1];

然后通過使用remove方法從字符串中刪除最后一個單詞來獲取字符串的其余部分。

我不想使用remove方法,是否有類似於上面的代碼集的方法來獲得一個不同的單詞串而沒有最后一個單詞和最后一個空格?

像這樣:

    String test = "This is a test";
    String firstWords = test.substring(0, test.lastIndexOf(" "));
    String lastWord = test.substring(test.lastIndexOf(" ") + 1);

你可以獲得lastIndexOf空格並使用子串,如下所示:

            String listOfWords = "This is a sentence";
        int index= listOfWords.lastIndexOf(" ");
        System.out.println(listOfWords.substring(0, index));
    System.out.println(listOfWords.substring(index+1));

輸出:

        This is a
        sentence

嘗試將String.lastIndexOf方法與String.substring結合使用。

String listOfWords = "This is a sentence";
String allButLast = listOfWords.substring(0, listOfWords.lastIndexOf(" "));

我在你的代碼中添加了一行,這里沒有刪除

String listOfWords = "This is a sentence";      
    String[] b = listOfWords.split("\\s+");
    String lastWord = b[b.length - 1];
    String rest = listOfWords.substring(0,listOfWords.indexOf(lastWord)).trim(); // Added
    System.out.println(rest);

這將滿足您的需求:

.split("\\s+[^\\s]+$|\\s+")

例如:

"This is a sentence".split("\\s+[^\\s]+$|\\s+");

返回:

[This, is, a]

public class StringArray {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    String sentense="this is a sentence";

    int index=sentense.lastIndexOf(" ");

    System.out.println(sentense.substring(0,index));

}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM