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

拜拜、爱过 提交于 2019-12-07 13:50:59

问题


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


回答1:


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



回答2:


You can use Regex.

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



回答3:


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



回答4:


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



回答5:


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


来源:https://stackoverflow.com/questions/16764314/how-to-use-substring-and-indexof-for-a-string-with-repeating-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!