简体   繁体   English

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

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

What is the easiest way to get every word in a string other than the last word in a string? 除了字符串中的最后一个单词之外,在字符串中获取每个单词的最简单方法是什么? Up until now I have been using the following code to get the last word: 到目前为止,我一直在使用以下代码来得到最后一句话:

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

And then getting the rest of the the string by using the remove method to remove the last word from the string. 然后通过使用remove方法从字符串中删除最后一个单词来获取字符串的其余部分。

I don't want to have to use the remove method, is there a way similar to the above set of code to get the a varying string of words without the last word and last space? 我不想使用remove方法,是否有类似于上面的代码集的方法来获得一个不同的单词串而没有最后一个单词和最后一个空格?

Like this: 像这样:

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

you could get the lastIndexOf the whitespace and use substring like below: 你可以获得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));

Output: 输出:

        This is a
        sentence

Try using the method String.lastIndexOf in combination with String.substring . 尝试将String.lastIndexOf方法与String.substring结合使用。

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

I added one line to your code, 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);

This will suit your needs: 这将满足您的需求:

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

For example: 例如:

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

Returns: 返回:

[This, is, a]

public class StringArray { 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