3

How can I substring the third number in the String below:

String val = "2020202030 or 303030303 or 303033303"; 

For two numbers the solution is as follows:

String val = "2020202030 or 303030303

firstNumber = val.substring(0,val.indexOf("or")-1);
secondNumber = val.substring(val.indexOf("or") + 3,val.length());

But how can I get the index of the second "or" in the String below?

String val = "2020202030 or 303030303 or 303033303";

firstNumber = val.substring(0,val.indexOf("or")-1);
secondNumber = val.substring(val.indexOf("or")-1,<index of second or >?);
thirdNumber= val.substring(<index of second or>?,val.length());
Eran
  • 387,369
  • 54
  • 702
  • 768
Dimitri
  • 1,924
  • 9
  • 43
  • 65

3 Answers3

7

Use split :

String[] numbers = val.split(" or ");

numbers[2] will contain the 3rd number.

If you prefer to use indexOf to get the index of the 2nd "or", use the int indexOf(String str, int fromIndex) variant.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

You can see this answer: https://stackoverflow.com/a/5034592/2668213

Then elaborate it just a bit. For example

int n_occurrences = 0

for (int index = val.indexOf("or");
     index >= 0;
     index = val.indexOf("or", index + 1))
{
    n_occurrences++;
    if (n_occurrences=2) 
       System.out.println(index);
}
Community
  • 1
  • 1
Federico Destefanis
  • 968
  • 1
  • 16
  • 27
0
String val = "2020202030 or 303030303 or 303033303";

String[] arr = val.split(" or ");

System.out.println(arr[0]); //2020202030

System.out.println(arr[1]); //303030303

System.out.println(arr[2]); //303033303
Akhil Menon
  • 306
  • 1
  • 9
  • 2
    Care to explain why it answers the question ? – Mel Dec 17 '15 at 08:59
  • Above I have used split function of java which returns the array, so when we split the above string with " or " we get the above string in array format with first element as "2020202030" and so on – Akhil Menon Dec 18 '15 at 04:26