Jocheved
Jocheved

Reputation: 1135

Split a string and get the second last word

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.

Upvotes: 5

Views: 25640

Answers (3)

nariuji
nariuji

Reputation: 278

I'm not sure but I think like this.

if your code is as follows, it does not work.

String string = "Hai,Hello,How,are,";
String[] bits = string.split(",");
 ↓
bits[]…{ "Hai","Hello","How","are" }
bits[bits.length-2]…"How"

This code works.

String string = "Hai,Hello,How,are,";
String[] bits = string.split(",", -1);
 ↓
bits[]…{ "Hai","Hello","How","are","" }
bits[bits.length-2]…"are"

Upvotes: 1

Amit Gupta
Amit Gupta

Reputation: 152

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.

Upvotes: 3

ninja.coder
ninja.coder

Reputation: 9648

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);

Upvotes: 7

Related Questions