-4

There is a string and I split it by whitespace and I want to get the last one.

String test = "Hey Hi Hello"; // Defining "test" String
test = test.split(" ")[2]; // Now "test" is "Hello"
System.out.print(test); // prints Hello

I should do this to get the last word of "test" String. But I know the length of the string. What should I do if I don't know the length of the String? What should I write between [ ] to get the last word?

For example when I get a data from an web page and I don't now the value is what.

kryger
  • 12,416
  • 8
  • 43
  • 65

3 Answers3

2

test.split returns an array of Strings. Just save it somewhere instead of using it immediately and check its length.

String test = "Hey Hi Hello";
String[] words = test.split(" ");
test = words[words.length - 1];
System.out.print(test);
Federico klez Culloca
  • 24,336
  • 15
  • 57
  • 93
0
String[] temp = test.split(" "); //this will split whole string into array using white space.
test = temp[temp.length-1]; //gets the element at the last index of temp array
StabCode
  • 96
  • 1
  • 6
-1

Another way is to avoid the split and cut the last word directly.

String text = "One Two Three";
text = text.substring(text.lastIndexOf(" ") + 1);

that way, you take the string from the last space till the end of the String

Frowner
  • 654
  • 6
  • 19