Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string and get the second last word

Tags:

java

string

split

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.

like image 892
Jocheved Avatar asked Dec 18 '22 18:12

Jocheved


2 Answers

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);
like image 191
user2004685 Avatar answered Dec 21 '22 09:12

user2004685


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.

like image 38
Amit Gupta Avatar answered Dec 21 '22 09:12

Amit Gupta