I am pretty new to Java and I have a little problem with formatting a String. I have add “\n” for a new line after every 18th char and I have to split these new lines into array indexes, 13 lines for each index.
My code so far:
String[] strings = str.split("\n");
String result;
for (int i = 1; i < strings.length; i++) {
i++;
if ((i % 13) == 0) {
result += strings[i];
} else {
result += strings[i] + "\n";
}
}
It doesn’t work as it should, I tested a bit around bit I don’t know how to do this, could someone help me please?
You’re incrementing
itwice in each loop – once in the increment expression of theforstatement, and once inside the loop itself. This meansiis always even, soi % 13is probably not 0 when you expect it to be. In addition, the first index of an array is 0, so you would currently ignore the first element. As a more minor point, I would advise using aStringBuilderinstead of appendingStrings: