Do double split in Java and get two sets of values

3

I'm getting this string in Java:

Respuesta1_10|Respuesta2_50|Respuesta4_90|Respuesta5_33

And I need to build two groups of values with it dynamically, since the amount of values separated by | is not fixed. The groups of values would be:

  • answers
  • status

To read them there are no problems, I do it like this:

    String str="Respuesta1_10|Respuesta2_50|Respuesta4_90|Respuesta5_33";
    String[] splitUno =str.split("\|");

    for (int x=0; x<splitUno.length; x++) 
    {
        String splitDos[]=splitUno[x].split("\_");
        System.out.println(splitDos[0]);
        System.out.println(splitDos[1]+"\n");
    }
}

At the exit I have:

Respuesta1
10

Respuesta2
50

Respuesta4
90

Respuesta5
33

But I would like to know if there is any easier way to create two sets of values without having to go through the for loop.

That is, to pass this:

Respuesta1_10|Respuesta2_50|Respuesta4_90|Respuesta5_33

Something like this:

String[] arrRespuestas = {"Respuesta1", "Respuesta2", "Respuesta3", "Respuesta5"};
int[] arrEstatus = {10, 50, 90, 33};
    
asked by A. Cedano 07.09.2017 в 06:27
source

1 answer

2

The input of Split is a Regex (regular expression), so if you put as input a regular expression that meets both separators.

an example would be:

public class HelloWorld{

 public static void main(String []args){
    String aux = "Resultado1_10|Resultado2_20";
    String[] spliteado = aux.split("[|]|_");
    for(String a:spliteado)
        System.out.println(a);
 }
}

Test the code online

Split Information

To try Regex online

    
answered by 07.09.2017 в 08:51