/* * [CollapseEmbeddedSpaces.java] * * Summary: Collapse embedded runs of spaces to a single space. * * Copyright: (c) 2002-2017 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.8+ * * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/ * * Version History: * 4.5 2009-02-26 add both Java string quoting and plain for Java search/regexes. */ package com.mindprod.quoter; /** * Collapse embedded runs of spaces to a single space. * * @author Roedy Green, Canadian Mind Products * @version 4.5 2009-02-26 add both Java string quoting and plain for Java search/regexes. * @since 2002-06-19 */ final class CollapseEmbeddedSpaces extends TextProcessor { /** * Collapse embedded runs of spaces to a single space. Leave leading and trailing spaces on each line as is. * * @param raw String to process, may contain embedded \ns. * * @return String with spaces collapsed. */ String process( String raw ) { if ( raw == null ) { return null; } char[] ca = new char[ raw.length() ]; int j = 0; // true if next space should be suppressed boolean suppress = false; // true if we are in the leading spaces of a line boolean inLeading = true; // count of how many spaces we recently suppressed int spacesSuppressed = 0; for ( int i = 0; i < raw.length(); i++ ) { char c = raw.charAt( i ); switch ( c ) { case '\t': case ' ': if ( inLeading || !suppress ) { ca[ j++ ] = c; suppress = true; } else { spacesSuppressed++; } break; case '\n': // We may have suppressed some trailing spaces we should not // have. // put them back. for ( ; spacesSuppressed > 0; spacesSuppressed-- ) { ca[ j++ ] = ' '; } ca[ j++ ] = c; inLeading = true; suppress = false; spacesSuppressed = 0; break; default: ca[ j++ ] = c; inLeading = false; suppress = false; spacesSuppressed = 0; break; } // end switch } // end for // If there was no trailing \n, // we may have suppressed some trailing spaces we should not have. // put them back. for ( ; spacesSuppressed > 0; spacesSuppressed-- ) { ca[ j++ ] = ' '; } if ( j != raw.length() ) { raw = new String( ca, 0, j/* count */ ); } return raw; } // end } // end CollapseEmbeddedSpaces