如何在前一个之后返回下一个indexOf?

时间:2013-04-24 11:25:35

标签: java string indexof

例如:

str = "(a+b)*(c+d)*(e+f)"
str.indexOf("(") = 0
str.lastIndexOf("(") = 12

如何在第二个括号中获取索引? (c + d)< - this

5 个答案:

答案 0 :(得分:8)

int first  = str.indexOf("(");
int next = str.indexOf("(", first+1);

查看API Documentation

答案 1 :(得分:8)

试试这个:

 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 :(得分:0)

  • 反复使用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;
            }
        }
    }

答案 3 :(得分:0)

你可以使用Apache Commons的StringUtils,在这种情况下它将是

StringUtils.indexof(str, ")", str.indexOf(")") + 1);

我们的想法是,在最后一个参数中你可以指定起始位置,这样就可以避免第一个“)”。

答案 4 :(得分:0)

我认为有更好的方法!!!

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);
相关问题