Putting char into a java string for each N characters

Try:

String s = // long string
s.replaceAll("(.{10})", "$1<br>");

EDIT: The above works… most of the time. I’ve been playing around with it and came across a problem: since it constructs a default Pattern internally it halts on newlines. to get around this you have to write it differently.

public static String insert(String text, String insert, int period) {
    Pattern p = Pattern.compile("(.{" + period + "})", Pattern.DOTALL);
    Matcher m = p.matcher(text);
    return m.replaceAll("$1" + insert);
}

and the astute reader will pick up on another problem: you have to escape regex special characters (like “$1”) in the replacement text or you’ll get unpredictable results.

I also got curious and benchmarked this version against Jon’s above. This one is slower by an order of magnitude (1000 replacements on a 60k file took 4.5 seconds with this, 400ms with his). Of the 4.5 seconds, only about 0.7 seconds was actually constructing the Pattern. Most of it was on the matching/replacement so it doesn’t even ledn itself to that kind of optimization.

I normally prefer the less wordy solutions to things. After all, more code = more potential bugs. But in this case I must concede that Jon’s version–which is really the naive implementation (I mean that in a good way)–is significantly better.

Leave a Comment