Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use substring and indexOf for a String with repeating characters?

I have the following String myString="city(Denver) AND state(Colorado)"; It has repeating "(" and ")"...

How can I retrieve state name, i.e. Colorado. I tried the following:

String state = myString.substring(myString.indexOf("state(")+1,myString.indexOf(")"));

But it give indexOutOfBoundException

Is there any way to specify that I need the second "(" in myString? I need the result: String state = "Colorado";

like image 446
Buras Avatar asked Dec 02 '22 19:12

Buras


1 Answers

Use lastIndexOf. Also increase the initial offset to allow for the number of characters in the sub-string state(:

String state = myString.substring(myString.indexOf("state(") + 6, myString.lastIndexOf(")"));
like image 197
Reimeus Avatar answered Dec 24 '22 00:12

Reimeus