'Split a String after every n characters ignoring whitespaces in java store it in arraylist

I have a string which I want to split after every n characters and store the same in an array of strings, but this should ignore all the whitespaces.

For example I have a string as follows,

String str = "This is a String which needs to be splitted after every 10 characters";

The output should be,

["This is a Str", "ing which nee", "ds to be split", "ted after ev", "ery 10 chara", "cters"]

(Edit) --> I am using the function below. How can I store this in an array of Strings.

As seen in the output it ignores indexes of all the whitespaces. Is there any way to do it in java.

public static String test(int cnt, String string) {
        AtomicInteger n = new AtomicInteger(cnt);
        return string
                .chars()
                .boxed()
                .peek(value -> {
                    if (!Character.isWhitespace(value)) {
                        n.decrementAndGet();
                    }
                })
                .takeWhile(value -> n.get() >= 0)
                .map(Character::toString)
                .collect(Collectors.joining());


Solution 1:[1]

I have used a standard approach with looping through the string and counting chars:

public static void main(String[] args) throws ParseException {
    String str = "This is a String which needs to be splitted after every 10 characters";
    System.out.println(split(str, 10));
}

public static List<String> split(String string, int splitAfter) {
    List<String> result = new ArrayList<String>();
    int startIndex = 0;
    int charCount = 0;
    for (int i = 0; i < string.length(); i++) {
        if (charCount == splitAfter) {
            result.add(string.substring(startIndex, i));
            startIndex = i;
            charCount = 0;
        }
        // only count non-whitespace characters
        if (string.charAt(i) != ' ') {
            charCount++;
        }
    }
    // check if startIndex is less than string length -> if yes, then last element wont be 10 characters long
    if (startIndex < string.length()) {
        result.add(string.substring(startIndex));
    }
    return result;
}

And the result differs slightly from what you posted, but looking at your expected result, it doesn't quite match the description anyways:

[This is a Str, ing which ne, eds to be spl, itted after,  every 10 cha, racters]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 XtremeBaumer