Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to get every word except the last word from a string

Tags:

java

string

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?

like image 266
Digitalwolf Avatar asked Jan 15 '13 10:01

Digitalwolf


People also ask

How do I split last word from string?

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.

How do I get just one word out of a 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.

How do you separate the last word from a string in Python?

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).


3 Answers

Like this:

    String test = "This is a test";
    String firstWords = test.substring(0, test.lastIndexOf(" "));
    String lastWord = test.substring(test.lastIndexOf(" ") + 1);
like image 101
jlordo Avatar answered Sep 30 '22 07:09

jlordo


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
like image 34
PermGenError Avatar answered Sep 30 '22 07:09

PermGenError


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

String listOfWords = "This is a sentence";
String allButLast = listOfWords.substring(0, listOfWords.lastIndexOf(" "));
like image 34
Kevin Bowersox Avatar answered Sep 30 '22 08:09

Kevin Bowersox