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

java, regex, string

Solution

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.

Problem

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"]

Original source