splitting string by comma and space in order to store them into 2 different array

I have below string and I wanted to convert into an array. I want to store all the names into an array and Store the choices that follows the names. For example,

String[] name = {"Home", "Sweet", "Smile, ..."}

I also want to store their choices as an array:

char[] choice = {'A', 'B', 'C', ...}

The source String is something like this:

String ls = "Home A,Sweet B,Smile C,Mind D";

FYI : I know how to split by comma, but I do not know how to get the choices. Any help, I will highly appreciate.

Answer

I did not use array lists since you said you used arrays.

  • first split the arrray on the the comma.
  • use that array length to create two other arrays for the names and choices.
  • the split on one or more spaces and assign the array element to the arrays.
String ls = "Home A,Sweet B,Smile C,Mind D";

String[] s = ls.split(",");
String[] names = new String[s.length];
String[] choices = new String[s.length];
for (int i = 0; i < s.length; i++) {
    String[] parts = s[i].split("\s+");
    names[i] = parts[0];
    choices[i] = parts[1];
}

System.out.println(Arrays.toString(names));
System.out.println(Arrays.toString(choices));
        

prints

[Home, Sweet, Smile, Mind]
[A, B, C, D]

But if you can use other data structures, an alternative to arrays is a map which lends itself to multiple choice type problems. Here, the key is the choice and it points to the name (or answer). This just splits the values twice and assigns the second array element to the key and the first to the value.

Map<String, String> map = Arrays.stream(ls.split(","))
        .map(str -> str.split("\s+"))
        .collect(Collectors.toMap(a -> a[1], a -> a[0]));

map.forEach((choice, name) -> System.out
        .println(choice + " -> " + name));

Prints

A -> Home
B -> Sweet
C -> Smile
D -> Mind

Leave a Reply

Your email address will not be published. Required fields are marked *