How to return the next indexOf after a previous?
Asked Answered
W

5

8

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

Womble answered 24/4, 2013 at 11:25 Comment(0)
C
11

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  "("
    }
Chop answered 24/4, 2013 at 11:28 Comment(2)
@baraky : index >= 0; is condition in for loop , so sorry i make rollback to my answer again :(Tongs
Still useful almost 7 years later :).Homans
O
17
int first  = str.indexOf("(");
int next = str.indexOf("(", first+1);

have a look at API Documentation

Okechuku answered 24/4, 2013 at 11:28 Comment(0)
C
11

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  "("
    }
Chop answered 24/4, 2013 at 11:28 Comment(2)
@baraky : index >= 0; is condition in for loop , so sorry i make rollback to my answer again :(Tongs
Still useful almost 7 years later :).Homans
L
0
  • 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;
            }
        }
    }
Lichenology answered 24/4, 2013 at 11:28 Comment(0)
A
0

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

Aquamanile answered 24/4, 2013 at 11:31 Comment(0)
B
0

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);
Bankston answered 24/4, 2013 at 11:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.