最简单的方法来获取除字符串中的最后一个单词之外的每个单词

时间:2013-01-15 10:28:48

标签: java string

除了字符串中的最后一个单词之外,在字符串中获取每个单词的最简单方法是什么?到目前为止,我一直在使用以下代码来得到最后一句话:

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

然后通过使用remove方法从字符串中删除最后一个单词来获取字符串的其余部分。

我不想使用remove方法,是否有类似于上面的代码集的方法来获取没有最后一个单词和最后一个空格的不同字符串?

6 个答案:

答案 0 :(得分:18)

像这样:

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

答案 1 :(得分:6)

你可以得到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

答案 2 :(得分:4)

尝试将方法String.lastIndexOfString.substring结合使用。

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

答案 3 :(得分:3)

我在你的代码中添加了一行,No remove here

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

答案 4 :(得分:2)

这将满足您的需求:

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

例如:

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

返回:

[This, is, a]

答案 5 :(得分:1)

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

}

}

相关问题