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 a varying string of words without the last word and last space?
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:
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(" "));
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 {
/**
* @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));
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.