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

狂风中的少年 提交于 2019-12-05 18:32:02

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

You can use Regex.

Matcher matcher = Pattern.compile("(state)(\(.*?\))").matcher(text);
String state = matcher.group(2);

You could just cut the string down, and do it in a sanboxed piece. This way if there are more trailing ")" nothing bad happens

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

You can use other version of String#indexOf(String str, int fromIndex) to specify from what position you would like to start searching ")".

int start = myString.indexOf("state(")+6;//6 is the length of "state(" - we dont want that part
int end = myString.indexOf(")", start);
String state = myString.substring(start, end);

Your problem is the first occurrence of ")" is before the occurrence of "state(", as it also appears after Denver.

If you need the last index, you could use lastIndexOf(), for both "(" and ")". If you need precisely the second occurrence, you could use the version of indexOf() that lets you specify an index where to start the search, and set that index to be the one after the first occurrence of your char, Like this:

 int firstOpenP = myString.indexOf("(");
 int firstClosedP = myString.indexOf(")");
 int secondOpenP = myString.indexOf("(", firstOpenP + 1);
 int secondClosedP = myString.indexOf(")", firstClosedP + 1);
 String state = myString.substring(secondOpenP + 1, secondClosedP);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!