Skip to content
Advertisement

How to split string of mulitdimensional array

i have string here String str1 = "{{1,2,3},{4,5,6},{7,8,9}}"

and the result i expect is like this

{1,2,3}
{4,5,6}
{7,8,9}

what method i use in java language? Thanks.


i tried with split method then put each array into an arraylist variable “data”. result :


1,2,3
,
4,5,6
,
7,8,9

and try to delete the data array that is empty and which only has a string value”,” result :


1,2,3
,
4,5,6
,
7,8,9
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
        at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
        at java.base/java.lang.String.charAt(String.java:712)
        at io.jhdf.examples.test2.lambda$0(test2.java:26)   
        at java.base/java.util.ArrayList.removeIf(ArrayList.java:1672)
        at java.base/java.util.ArrayList.removeIf(ArrayList.java:1660)
        at io.jhdf.examples.test2.main(test2.java:26)

and this is my code :

ArrayList<String> data = new ArrayList<String>();

        String str1 = "{{1,2,3},{4,5,6},{7,8,9}}";
        String[] arrOfStr1 = str1.split("[{}]");

        //System.out.println(arrOfStr[2].length());

        for (String a1 : arrOfStr1){
            data.add(a1);
            System.out.println(a1);
        }
        data.removeIf(n -> (n.charAt(0)) == ',');

Advertisement

Answer

You get the StringIndexOutOfBoundsException because you have some empty strings in your arrOfStr1 array. The n.charAt(0) expression is causing the exception because there is no characters in some of the strings. Use the debugger to see whats really in the data array before you try to remove the single commas.

Anyways, here is the fix, modify one line in your code:

 data.removeIf(n -> n.equals("") || ( n.charAt(0)) == ',');

And by the way you could also use Streams. The whole code could also look like that:

String str1 = "{{1,2,3},{4,5,6},{7,8,9}}";

    List<String> data =  Arrays.stream(str1.split("[{}]"))
            .filter(n -> !n.equals("") && ( n.charAt(0)) != ',')
            .collect(Collectors.toList());
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement