-3

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

user3714696
  • 91
  • 2
  • 8

3 Answers3

5

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, "");
Limnic
  • 1,826
  • 1
  • 20
  • 45
2
String w =  "hello is my new car ".trim();
String lastWord = test.substring(test.lastIndexOf(" ")+1);
Danilo Dughetti
  • 1,360
  • 1
  • 11
  • 18
1

You can split by whitespace and take the last element.

String[] s = "hello is my new car".split(" ");

String lastWord = s[lenght-1];
Arc676
  • 4,445
  • 3
  • 28
  • 44
Victor Viola
  • 575
  • 1
  • 4
  • 14