-1

I'm trying to split a string into different parts each having x amount of characters in it. How can I go along doing this?

EDIT: I've managed to figure itout thanks to @amith down below however I'm unsure how to make it not split words, any ideas?

Thanks, - Exporting.

2 Answers2

0
List<String> splitString(int interval, String str) {
    int length = str.length();
    List<String> split = new ArrayList<>();
    if(length < interval) {
        split.add(str);
    } else {
        for(int i=0;i<length;i+=interval) {
            int endIndex = i + interval;
            if(endIndex > length) {
                endIndex = length;
            }
            String substring = str.substring(i, endIndex);
            split.add(substring);
        }
    }
    return split;
}

This is a sample code to split string at regular intervals

amith
  • 399
  • 1
  • 2
  • 11
0

If result is an array of char, try this:

public static char[] split(String str, int numChar) {
    char[] s = str.toCharArray();
    if (numChar >= str.length()) {
        return s;
    }
    char[] r = new char[numChar];
    System.arraycopy(s, 0, r, 0, numChar);
    return r;
}

Or if result is a String, try this:

public static String split(String str, int numChar) {
    char[] s = str.toCharArray();
    if (numChar >= str.length()) {
        return String.copyValueOf(s);
    }
    char[] r = new char[numChar];
    System.arraycopy(s, 0, r, 0, numChar);
    return String.copyValueOf(r);
}

Please note that two of above methods do not change the original String.