Search code examples
javastringsplitchars

how to split a string to several Strings by Specified number of characters in java


I have a hypothetical string with 2500 characters. (myString.length=2500) and I want to split it to several strings per 500 chars and assign this new strings to an Array string.


Solution

  • Simplest way is to find the total split strings, and then inchworm up through the values adding the sub-strings to an ArrayList or something. Probably look a lot like this:

    int splits = myString.length()/divisor;
    int first = 0;
    int second = divisor;
    for (int i = 0; i < splits; i++) {
        arrayList.add(myString.substring(first, second));
        first += divisor;
        second += divisor;
    }