如何返回上一个之后的下一个indexOf?
例如:
str = "(a+b)*(c+d)*(e+f)" str.indexOf("(") = 0 str.lastIndexOf("(") = 12
如何在第二个括号中获取索引? (c + d)< – 这个
试试这个 :
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 "(" }
int first = str.indexOf("("); int next = str.indexOf("(", first+1);
看看API文档
你可以使用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);