How can I get the last word of an string if my string is like that "hello is my new car "(after the word car there is an white space).
I want to know how remove it too.
Thank you so much
How can I get the last word of an string if my string is like that "hello is my new car "(after the word car there is an white space).
I want to know how remove it too.
Thank you so much
For this case, you can first trim the string:
String s = "hello is my new car ".trim();
Trim removes all trailing and leading spaces.
Then you can split the String like:
String[] words = s.split(" ");
Once you have that you can simply get the last index which will be the last word:
String lastWord = words[words.length - 1];
Ofcourse, for more complex issues regex would be a better option.
UPDATE:
In order to remove this word from the string you can simply replace it:
String withoutWord = s.replace(lastWord, "");
String w = "hello is my new car ".trim();
String lastWord = test.substring(test.lastIndexOf(" ")+1);
You can split by whitespace and take the last element.
String[] s = "hello is my new car".split(" ");
String lastWord = s[lenght-1];