0

Firstly, I know that there may be a duplicate but I do not understand them, so please don't mark this as a duplicate!

I wish to split the strings in an array (see below) into characters:

Original:

String original = "0, 0, 0, 0 | 1, 1, 1, 1 | 2, 2, 2, 2"

Array:

String[] array2 = {"0, 0, 0, 0", "1, 1, 1, 1", "2, 2, 2, 2"}

Result that I want:

String[] arrayprime = {"0", "0", "0", "0", "1", "1", "1", "1", "2", "2", "2", "2"}

How would you do this? I thought of

String[] array2 = original.split("\\|");
String[] arrayprime = array2.split(", ");

but it doesn't seem to work (says "Cannot find symbol").

Should I make the array (array2) into a String (if so, how)? And then split again?

matematika
  • 85
  • 1
  • 9

3 Answers3

3

It looks like you want to split on ", " OR " | ".

Since split supports regular expression you can write it as

String[] array = yourText.split(", | \\| ");
//                                 ^-OR operator which creates 
//                                   alternation between ", " and " | "
Pshemo
  • 122,468
  • 25
  • 185
  • 269
2

you can use character classes which required no escaping in this case

    String original = "0, 0, 0, 0 | 1, 1, 1, 1 | 2, 2, 2, 2";
    String arr[]=original.split("[|,]");
    System.out.println(Arrays.toString(arr));
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
1

Your error is in this line

String[] arrayprime = array2.split(" ");

You cannot use split method on array. Split method is on String. So basically you have to iterate over array2 and apply split on each String.

Or simply use regex

String[] array2 = original.split("\\||,");

Note that you'll have spaces in your Strings after using this as your initial string have spaces. Please consider trimming them to get desired output.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307