Search code examples
javasplitline-separator

How do I split a string in Java with System.lineseparator AND commas?


I have a file of integers, similar to the following:

9,4, 11, 2, 40, 17,11,20,9,20, 15,13, 19, 35,12,14, 13,1, 0,20,9, 1
40,29, 40, 25, 30, 12, 31, 27,39,7,37,15,31,1,26, 36,36, 35,30, 5, 24
25, 9, 20,31, 18, 11, 33,22, 39,40, 4, 23,34, 13, 16, 19, 22,3, 36, 2 
18,23,16,2, 28,0, 9,15, 5,22, 35, 40,2,14,18, 33, 22,16,12, 35, 37,38,2
0,24, 29,37, 13,3, 9,18,39, 8,24,9,1,39,22,2, 27, 38,5, 38, 6, 11,13,10 
31,25,22, 16,2, 1,25, 26,30, 10, 36, 18,33,31, 27, 30,25, 12, 5,5,2, 35
7,7,36,16, 33,12,34, 19, 29, 40,5,7

The integers are separated by commas and the rows are separated by the System.lineseparator().

The TextFile is converted into a string by the use of the readFile method. Now I would like to convert that string into a 1D array of strings of the integer values.

However, when I split the string by commas (",") I loose the values at the end of a row as they are not separated by commas but by the lineseparator. How can I solve this problem?

I tried to separate it only by commas, as I thought that the lineseparator gets automatically read by the split. However, this is not the case. Also Java does not allow to split a string twice.


Solution

  • Assuming you want to use them as ints, you can split on white space while also splitting on a comma and the line separator.

        String s = """
    9,4, 11, 2, 40, 17,11,20,9,20, 15,13, 19, 35,12,14, 13,1, 0,20,9, 1
    40,29, 40, 25, 30, 12, 31, 27,39,7,37,15,31,1,26, 36,36, 35,30, 5, 24
    25, 9, 20,31, 18, 11, 33,22, 39,40, 4, 23,34, 13, 16, 19, 22,3, 36, 2 
    18,23,16,2, 28,0, 9,15, 5,22, 35, 40,2,14,18, 33, 22,16,12, 35, 37,38,2
    0,24, 29,37, 13,3, 9,18,39, 8,24,9,1,39,22,2, 27, 38,5, 38, 6, 11,13,10 
    31,25,22, 16,2, 1,25, 26,30, 10, 36, 18,33,31, 27, 30,25, 12, 5,5,2, 35
    7,7,36,16, 33,12,34, 19, 29, 40,5,7
    """;
    
    String[] stringArray = s.split("\\R|[\\s,]+");       
    int count = 1;
    for (String str : stringArray) {
        System.out.print(str + " " );
        if (count % 20 == 0) {
            System.out.println();
        }
        count++;
    }
    

    prints no more than 20 per line to avoid horizontal scrolling.

    9 4 11 2 40 17 11 20 9 20 15 13 19 35 12 14 13 1 0 20 
    9 1 40 29 40 25 30 12 31 27 39 7 37 15 31 1 26 36 36 35 
    30 5 24 25 9 20 31 18 11 33 22 39 40 4 23 34 13 16 19 22 
    3 36 2 18 23 16 2 28 0 9 15 5 22 35 40 2 14 18 33 22 
    16 12 35 37 38 2 0 24 29 37 13 3 9 18 39 8 24 9 1 39 
    22 2 27 38 5 38 6 11 13 10 31 25 22 16 2 1 25 26 30 10 
    36 18 33 31 27 30 25 12 5 5 2 35 7 7 36 16 33 12 34 19 
    29 40 5 7 
    

    If you want to convert them to an int array, do it like so. Note you need to eliminate white space to avoid a NumberFormatException.

    int[] intArray = Arrays.stream(s.split("\\R|[\\s,]+"))
                    .mapToInt(Integer::parseInt).toArray();