package votorola.g.lang; // Copyright 2008, Michael Allan. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Votorola Software"), to deal in the Votorola Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicence, and/or sell copies of the Votorola Software, and to permit persons to whom the Votorola Software is furnished to do so, subject to the following conditions: The preceding copyright notice and this permission notice shall be included in all copies or substantial portions of the Votorola Software. THE VOTOROLA SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE VOTOROLA SOFTWARE OR THE USE OR OTHER DEALINGS IN THE VOTOROLA SOFTWARE. /** StringBuilder utilities. */ public @ThreadSafe final class StringBuilderX { private StringBuilderX() {} /** Clears the string builder. * * @return the same string builder. */ public static StringBuilder clear( final StringBuilder b ) { b.delete( 0, b.length() ); return b; } /** Collapses contiguous runs of whitespace to a single space each, and trims all * whitepace from the ends. * * @return the same string builder. */ public static StringBuilder collapseAndTrim( final StringBuilder b ) { boolean wasWhitespaceLast = true; // thus to trim all trailing spaces for( int c = b.length() - 1; c >= 0; --c ) { final char ch = b.charAt( c ); final boolean isWhitespace = Character.isWhitespace( ch ); if( isWhitespace ) { if( wasWhitespaceLast ) b.deleteCharAt( c ); // collapse all whitespace else if( ch != ' ' ) b.setCharAt( c, ' ' ); // to single space char } wasWhitespaceLast = isWhitespace; } if( b.length() > 0 && wasWhitespaceLast ) b.deleteCharAt( 0 ); // trim leading space, if any (can only be one left) return b; } /** Trims all whitepace from the ends. * * @return the same string builder. */ public static StringBuilder trim( final StringBuilder b ) { for( ;; ) { final int length = b.length(); if( length == 0 ) return b; final char ch = b.charAt( 0 ); if( !Character.isWhitespace( ch )) { if( length == 1 ) return b; break; } b.deleteCharAt( 0 ); } for( ;; ) { final int last = b.length() - 1; final char ch = b.charAt( last ); if( !Character.isWhitespace( ch )) break; b.deleteCharAt( last ); if( last == 0 ) break; } return b; } }