How to return the next indexOf after a previous?

房东的猫 提交于 2019-12-05 18:49:02

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  "("
    }
wrm
int first  = str.indexOf("(");
int next = str.indexOf("(", first+1);

have a look at API Documentation

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 ")".

  • 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;
            }
        }
    }

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