-3

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,906
  • 8
  • 44
  • 65

2 Answers2

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
  • 26,308
  • 17
  • 56
  • 95
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
  • 106
  • 1
  • 6