/** * This will truncate sequences in a string of the same character that exceed the maximum * allowed length. * * @return The same string or a new one if truncation is done. */ public static String truncateSequencesIfNecessary(String text, int maxConsecutiveLength) { char prev = 0; int sequenceCount = 1; for (int i = 0, m = text.length(); i < m ; i++) { char curr = text.charAt(i); if (prev == curr) { sequenceCount++; if (sequenceCount > maxConsecutiveLength) { return truncateSequences(text, maxConsecutiveLength, i); } } else { sequenceCount = 1; prev = curr; } } return text; }