如何在Java中分隔最后一个单词和其余所有单词?

时间:2019-10-21 08:54:00

标签: java string

如果用户输入多个空格,最简单的方法是获取最后一个单词并保留所有单词?

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

我希望输出类似lastWord = sentencefirstWords = this is a

8 个答案:

答案 0 :(得分:2)

String listOfWords = "This is a sentence";

String lastWord = listOfWords.replaceFirst("^((.*\\s+)?)(^\\S+)\\s*$", "$3");
String firstWords = listOfWords.replaceFirst("^((.*\\s+)?)(^\\S+)\\s*$", "$2").trim();

将最后一个单词标识为(\\S+)\\s*$:非空格,可能在末尾($)后面加空格。

  • 没有单词时,工作
  • 只有一个字时有效
  • 在末尾有空格时起作用

答案 1 :(得分:1)

这是为您快速解决的问题。检查以下代码。

输入:

这是一个句子

输出:

第一句话:这是

最后一句话:句子

    String test = "This is a sentence";
    String first = test.substring(0, test.lastIndexOf(" "));
    String last = test.substring(test.lastIndexOf(" ") + 1);
    System.out.println("First Words :" + first);
    System.out.print("Last Words :" + last);

希望此解决方案有效。

答案 2 :(得分:1)

要使用正则表达式添加另一个答案以在最后一个空格处拆分句子:

String listOfWords = "This is a sentence";
String[] splited = listOfWords.split("\\s(?=[^\\s]+$)");
System.out.println(Arrays.toString(splited));

//output [This is a, sentence]

答案 3 :(得分:0)

我并不是说这是一个很好的解决方案,但是您可以通过以下方式获得解决方案:

public static void main(String[] args) {
    String listOfWords = "   This   is   a     sentence   ";
    listOfWords = listOfWords.trim().replaceAll("\\s+", " ");
    String[] b = listOfWords.split("\\s+");
    String lastWord = b[b.length - 1];

    String firstWord = listOfWords.substring(0, listOfWords.length() - lastWord.length());
    System.out.println(lastWord.trim());
    System.out.println(firstWord.trim());
}

答案 4 :(得分:0)

您可以使用

System.arraycopy(Object[] src, int srcStartIndex, Object[] dest, int dstStartIndex, int lengthOfCopiedIndices);

请检查以下内容:

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

String[] others = Arrays.copyOfRange(b, 0, b.length - 1);
//You can test with this
for(int i=0;i< others.length;i++){
    System.out.println(others[i]);
}

答案 5 :(得分:0)

    String listOfWords = "This is a sentence";
    String first=listOfWords.substring(0,listOfWords.lastIndexOf(' '));
    String last=listOfWords.substring(listOfWords.lastIndexOf(' ')+1);

希望这对您有所帮助。

答案 6 :(得分:0)

您也可以按照以下步骤进行操作:

import java.util.Arrays;

public class Test {
    public static void main(String args[]) {
        String listOfWords = "     This      is       a            sentence";
        String[] b = listOfWords.split("\\s+");
        for(int i=0;i<b.length;i++)
            b[i]=b[i].trim();
        String lastWord = b[b.length - 1];      
        String []fw= new String[b.length - 2];
        System.arraycopy(b, 1, fw, 0, b.length-2);      
        System.out.println("First words: "+Arrays.toString(fw));
        System.out.println("Last word: "+lastWord);
    }
}

输出:

First words: [This, is, a]
Last word: sentence

答案 7 :(得分:0)

您可以使用正则表达式实现完美匹配

==============================================
                      Dependent variable:     
                  ----------------------------
                              mpg             
----------------------------------------------
cyl                         -0.102**          
                            (0.043)           

hp                           -0.001           
                            (0.001)           

Constant                    3.790***          
                            (0.146)           

----------------------------------------------
Observations                   32             
Log Likelihood              -84.287           
theta             894,228.600 (23,863,364.000)
Akaike Inf. Crit.           174.574           
==============================================
Note:              *p<0.1; **p<0.05; ***p<0.01

模式“ ^(。+?)(\ s +)([^ \ s] +?)$”的工作方式如下

^(。+?)-匹配所有字符,包括从句子开头(^)开始的空格

(\ s +)-匹配多个空格(如果存在)

([[^ \ s] +?)$-忽略最后一个空格以匹配最后一个单词($)

输出:

    String listOfWords = "This is a sentence";
    Pattern r = Pattern.compile("^(.+?)(\\s+)([^\\s]+?)$");
    Matcher m = r.matcher(listOfWords);
    while(m.find()){
       System.out.println("Last word : "+ m.group(3));
       System.out.println("Remaining words : "+ m.group(1));
    } 
相关问题