问题
For example:
str = "(a+b)*(c+d)*(e+f)"
str.indexOf("(") = 0
str.lastIndexOf("(") = 12
How to get the index in second bracket? (c+d) <- this
回答1:
Try this :
String word = "(a+b)*(c+d)*(e+f)";
String c = "(";
for (int index = word.indexOf(c);index >= 0; index = word.indexOf(c, index + 1)) {
System.out.println(index);//////here you will get all the index of "("
}
回答2:
int first = str.indexOf("(");
int next = str.indexOf("(", first+1);
have a look at API Documentation
回答3:
You can use StringUtils from Apache Commons, in this case it would be
StringUtils.indexof(str, ")", str.indexOf(")") + 1);
The idea is that in the last parameter you can specify the starting position, so you can avoid the first ")".
回答4:
- Use
charAt()repeatedly - Use
indexOf()repeatedly
Try this simple solution for general purpose:
int index =0;
int resultIndex=0;
for (int i = 0; i < str.length(); i++){
if (str.charAt(i) =='('){
index++;
if (index==2){
resultIndex =i;
break;
}
}
}
回答5:
I think have better method !!!
String str = "(a+b)*(c+d)*(e+f)";
str = str.replace(str.substring(str.lastIndexOf("*")), "");
int idx = str.lastIndexOf("(");
and "(c+d)" :
str = str.substring(idx);
来源:https://stackoverflow.com/questions/16190734/how-to-return-the-next-indexof-after-a-previous