Java – Substring : get index of “or” occurrence in string

Substring : get index of “or” occurrence in string… here is a solution to the problem.

Substring : get index of “or” occurrence in string

How to substring the third number in the following String:

String val = "2020202030 or 303030303 or 303033303"; 

The solution for two numbers is as follows:

String val = "2020202030 or 303030303

firstNumber = val.substring(0,val.indexOf("or")-1);
secondNumber = val.substring(val.indexOf("or") + 3,val.length());

But how to get the index of the second “or” in the String below?

String val = "2020202030 or 303030303 or 303033303";

firstNumber = val.substring(0,val.indexOf("or")-1);
secondNumber = val.substring(val.indexOf("or")-1,<index of second or >?);
thirdNumber= val.substring(<index of second or>?,val.length());

Solution

Use splitting:

String[] numbers = val.split(" or ");

numbers[2] will contain a third number.

If you prefer to use indexOf to get the index of the second “or”, use the int indexOf(String str, int fromIndex) variant.

Related Problems and Solutions