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.

2

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.