Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string into 2 at the last occurrence of an underscore character [closed]

Tags:

java

string

regex

Given a string with a number of underscore characters, how can it be split into two substrings around the last underscore character?

eg. "a_b_c" => ["a_b", "_c"]

like image 537
agarwal_achhnera Avatar asked Jun 03 '14 12:06

agarwal_achhnera


1 Answers

You can use lastIndexOf on String which returns you the index of the last occurrence of a chain of caracters.

String thing = "132131_12313_1321_312";
int index = thing.lastIndexOf("_");
String yourCuttedString = thing.substring(0, index);

It returns -1 if the occurrence is not found in the String.

like image 105
lpratlong Avatar answered Sep 21 '22 04:09

lpratlong