Reputation: 493
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?
Upvotes: 8
Views: 33430
Reputation: 6572
I added one line to your code. Nothing was removed 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);
Upvotes: 3
Reputation: 31
public class StringArray {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String sentence = "this is a sentence";
int index = sentence.lastIndexOf(" ");
System.out.println(sentence.substring(0, index));
}
}
Upvotes: 2
Reputation: 46408
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
Upvotes: 8
Reputation: 48817
This will suit your needs:
.split("\\s+[^\\s]+$|\\s+")
For example:
"This is a sentence".split("\\s+[^\\s]+$|\\s+");
Returns:
[This, is, a]
Upvotes: 2
Reputation: 94469
Try using the method String.lastIndexOf
in combination with String.substring
.
String listOfWords = "This is a sentence";
String allButLast = listOfWords.substring(0, listOfWords.lastIndexOf(" "));
Upvotes: 6
Reputation: 37813
Like this:
String test = "This is a test";
String firstWords = test.substring(0, test.lastIndexOf(" "));
String lastWord = test.substring(test.lastIndexOf(" ") + 1);
Upvotes: 24