/** * This method appends a string to a string builder and collapses contiguous * white space is a single space. * * This is equivalent to: * destination.append(source.replaceAll("\\s+", " ")) * but does not create a Pattern object that needs to compile the match * string; it also prevents us from having to make a Matcher object as well. * */ public static void appendCompactedString(final StringBuilder destination, final String source) { boolean previousIsWhiteSpace = false; int length = source.length(); for (int i = 0; i < length; i++) { char ch = source.charAt(i); if (isWhiteSpace(ch)) { if (previousIsWhiteSpace) { continue; } destination.append(CHAR_SPACE); previousIsWhiteSpace = true; } else { destination.append(ch); previousIsWhiteSpace = false; } } }
/** * This method appends a string to a string builder and collapses contiguous * white space is a single space. * * This is equivalent to: * destination.append(source.replaceAll("\\s+", " ")) * but does not create a Pattern object that needs to compile the match * string; it also prevents us from having to make a Matcher object as well. * */ public static void appendCompactedString(final StringBuilder destination, final String source) { boolean previousIsWhiteSpace = false; int length = source.length(); for (int i = 0; i < length; i++) { char ch = source.charAt(i); if (isWhiteSpace(ch)) { if (previousIsWhiteSpace) { continue; } destination.append(CHAR_SPACE); previousIsWhiteSpace = true; } else { destination.append(ch); previousIsWhiteSpace = false; } } }
/** * This method appends a string to a string builder and collapses contiguous * white space is a single space. * * This is equivalent to: * destination.append(source.replaceAll("\\s+", " ")) * but does not create a Pattern object that needs to compile the match * string; it also prevents us from having to make a Matcher object as well. * */ public static void appendCompactedString(final StringBuilder destination, final String source) { boolean previousIsWhiteSpace = false; int length = source.length(); for (int i = 0; i < length; i++) { char ch = source.charAt(i); if (isWhiteSpace(ch)) { if (previousIsWhiteSpace) { continue; } destination.append(CHAR_SPACE); previousIsWhiteSpace = true; } else { destination.append(ch); previousIsWhiteSpace = false; } } }