Java 如何在上一个之后返回下一个 indexOf?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16190734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return the next indexOf after a previous?
提问by rustock
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
如何获得第二个括号中的索引?(c+d) <- 这个
采纳答案by Alya'a Gamal
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 "("
}
回答by wrm
int first = str.indexOf("(");
int next = str.indexOf("(", first+1);
have a look at API Documentation
看看API 文档
回答by Achintya Jha
- Use
charAt()
repeatedly - Use
indexOf()
repeatedly
charAt()
反复使用indexOf()
反复使用
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;
}
}
}
回答by maxivis
You can use StringUtilsfrom Apache Commons, in this case it would be
您可以使用Apache Commons 中的StringUtils,在这种情况下,它将是
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 ")".
这个想法是在最后一个参数中你可以指定起始位置,这样你就可以避免第一个“)”。
回答by VincentLamoute
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)" :
和 "(c+d)" :
str = str.substring(idx);