I have a string "Hai,Hello,How,are,you"
What I needed is I need the second last word that is "are"
String string = "Hai,Hello,How,are,you";
String[] bits = string.split(",");
String lastWord = bits[bits.length-1]
tvs.setText(lastWord);
But when I did like this:
String lastWord = bits[bits.length-2];
I am not getting the second last word.
What you need is String lastWord = bits[bits.length-2];
because bits[bits.length-1];
will return you the last word and not the second last.
This is because indexing of array starts with 0
and ends in length-1
.
Here is the updated code snippet:
String string = "Hai,Hello,How,are,you";
String[] bits = string.split(",");
String lastWord = bits[bits.length - 2];
tvs.setText(lastWord);
Here first you have to find out index of character ',' from last. And after that second character ',' from the last. After that you can find out sub string between them .
String string = "Hai,Hello,How,are,you";
int lastIndex,secondLastIndex;
lastIndex=string.lastIndexOf(',');
secondLastIndex=string.lastIndexOf(',',lastIndex-1);
System.out.println(string.substring(secondLastIndex+1,lastIndex));
try it will work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With