4

I have a problem with String.split(String regex). I want to split my string in parts of 4 characters each.

String stringa = "1111110000000000"
String [] result = stringa.split("(?<=\\G....)")

When I print result I expect 1111,1100,0000,0000 but result is 1111,110000000000. How can I resolve? Thanks.

DDJoe
  • 41
  • 1
  • 5

1 Answers1

2

Here a solution without regex -

You begin at the string's end, extract 4 or less characters and prepend them to a List:

public static void main (String[] args) {
    String stringa = "11111110000000000";
    List<String> result = new ArrayList<>();

    for (int endIndex = stringa.length(); endIndex  >= 0; endIndex  -= 4) {
        int beginIndex = Math.max(0, endIndex - 4);
        String str = stringa.substring(beginIndex, endIndex);
        result.add(0, str);
    }

    System.out.println(result);
}

Which results in the output:

[1, 1111, 1100, 0000, 0000]
Alexander Farber
  • 21,519
  • 75
  • 241
  • 416