The easiest way to get every word except the last word from a string

What is the easiest way to get every word in a line different from the last word in a line? So far, I have used 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 leaving the rest of the line using the remove method to remove the last word from the line.

I don’t want to use the remove method, is there a way, similar to the above code set, to get a variable of a string of words without the last word and last space?

+6
source share
6 answers

Like this:

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

you can get lastIndexOf space and use a substring as below:

  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 
+5
source

Try using the String.lastIndexOf method in conjunction with String.substring .

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

I added one line to your code, do not delete 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); 
+3
source

This will fit your needs:

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

For instance:

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

Return:

 [This, is, a] 
+2
source

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

}

+1
source

All Articles