【发布时间】:2013-04-24 11:25:34
【问题描述】:
例如:
str = "(a+b)*(c+d)*(e+f)"
str.indexOf("(") = 0
str.lastIndexOf("(") = 12
如何获取第二个括号中的索引? (c+d)
【问题讨论】:
例如:
str = "(a+b)*(c+d)*(e+f)"
str.indexOf("(") = 0
str.lastIndexOf("(") = 12
如何获取第二个括号中的索引? (c+d)
【问题讨论】:
int first = str.indexOf("(");
int next = str.indexOf("(", first+1);
【讨论】:
试试这个:
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 "("
}
【讨论】:
index >= 0; 是 for 循环中的条件,所以很抱歉我再次回滚我的答案:(
您可以使用来自 Apache Commons 的 StringUtils,在这种情况下是
StringUtils.indexof(str, ")", str.indexOf(")") + 1);
想法是在最后一个参数中可以指定起始位置,这样就可以避免第一个“)”。
【讨论】:
charAt()
indexOf()
试试这个简单的通用解决方案:
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;
}
}
}
【讨论】:
我觉得有更好的方法!!!
String str = "(a+b)*(c+d)*(e+f)";
str = str.replace(str.substring(str.lastIndexOf("*")), "");
int idx = str.lastIndexOf("(");
和“(c+d)”:
str = str.substring(idx);
【讨论】: