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.
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 string of words without the last word and last space?
Using the split() Method As we have to get the last word of a string, we'll be using space (” “) as a regular expression to split the string. This will return “day”, which is the last word of our input string.
Call the split() method passing it a string containing an empty space as a parameter. The split method will return an array containing the words in the string.
Take an empty string, newstring. Traverse the string in reverse order and add character to newstring using string concatenation. Break the loop till we get first space character. Reverse newstring and return it (it is the last word in the sentence).
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 white space and use a substring like 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
Try using the method String.lastIndexOf
in combination with String.substring
.
String listOfWords = "This is a sentence";
String allButLast = listOfWords.substring(0, listOfWords.lastIndexOf(" "));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With