How to return the next indexOf after a previous?

蓝咒 提交于 2019-12-07 14:10:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!