Java Tutorial/Data Type/String Format

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

Abbreviates a String using ellipses.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

public class Main {

 // Abbreviating
 //-----------------------------------------------------------------------
 /**
  * Abbreviates a String using ellipses. This will turn
  * "Now is the time for all good men" into "Now is the time for..."
  *
  * Specifically:
*
    *
  • If str is less than maxWidth characters * long, return it.
  • *
  • Else abbreviate it to (substring(str, 0, max-3) + "...").
  • *
  • If maxWidth is less than 4, throw an * IllegalArgumentException.
  • *
  • In no case will it return a String of length greater than * maxWidth.
  • *
  * 
  *
*
   * StringUtils.abbreviate(null, *)      = null
   * StringUtils.abbreviate("", 4)        = ""
   * StringUtils.abbreviate("abcdefg", 6) = "abc..."
   * StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
   * StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
   * StringUtils.abbreviate("abcdefg", 4) = "a..."
   * StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
   * 
  *
  * @param str  the String to check, may be null
  * @param maxWidth  maximum length of result String, must be at least 4
  * @return abbreviated String, null if null String input
  * @throws IllegalArgumentException if the width is too small
  * @since 2.0
  */
 public static String abbreviate(String str, int maxWidth) {
     return abbreviate(str, 0, maxWidth);
 }
 /**
  * Abbreviates a String using ellipses. This will turn
  * "Now is the time for all good men" into "...is the time for..."
  *
  * Works like abbreviate(String, int), but allows you to specify
  * a "left edge" offset.  Note that this left edge is not necessarily going to
  * be the leftmost character in the result, or the first character following the
  * ellipses, but it will appear somewhere in the result.
  *
  * In no case will it return a String of length greater than
  * maxWidth.
  *
*
   * StringUtils.abbreviate(null, *, *)                = null
   * StringUtils.abbreviate("", 0, 4)                  = ""
   * StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
   * StringUtils.abbreviate("abcdefghijklmno", 0, 10)  = "abcdefg..."
   * StringUtils.abbreviate("abcdefghijklmno", 1, 10)  = "abcdefg..."
   * StringUtils.abbreviate("abcdefghijklmno", 4, 10)  = "abcdefg..."
   * StringUtils.abbreviate("abcdefghijklmno", 5, 10)  = "...fghi..."
   * StringUtils.abbreviate("abcdefghijklmno", 6, 10)  = "...ghij..."
   * StringUtils.abbreviate("abcdefghijklmno", 8, 10)  = "...ijklmno"
   * StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
   * StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
   * StringUtils.abbreviate("abcdefghij", 0, 3)        = IllegalArgumentException
   * StringUtils.abbreviate("abcdefghij", 5, 6)        = IllegalArgumentException
   * 
  *
  * @param str  the String to check, may be null
  * @param offset  left edge of source String
  * @param maxWidth  maximum length of result String, must be at least 4
  * @return abbreviated String, null if null String input
  * @throws IllegalArgumentException if the width is too small
  * @since 2.0
  */
 public static String abbreviate(String str, int offset, int maxWidth) {
     if (str == null) {
         return null;
     }
     if (maxWidth < 4) {
         throw new IllegalArgumentException("Minimum abbreviation width is 4");
     }
     if (str.length() <= maxWidth) {
         return str;
     }
     if (offset > str.length()) {
         offset = str.length();
     }
     if ((str.length() - offset) < (maxWidth - 3)) {
         offset = str.length() - (maxWidth - 3);
     }
     if (offset <= 4) {
         return str.substring(0, maxWidth - 3) + "...";
     }
     if (maxWidth < 7) {
         throw new IllegalArgumentException("Minimum abbreviation width with offset is 7");
     }
     if ((offset + (maxWidth - 3)) < str.length()) {
         return "..." + abbreviate(str.substring(offset), maxWidth - 3);
     }
     return "..." + str.substring(str.length() - (maxWidth - 3));
 }

}</source>





Abbreviates a String using ellipses in both sides.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

public class Main {

 // Abbreviating
 //-----------------------------------------------------------------------
 /**
  * Abbreviates a String using ellipses. This will turn
  * "Now is the time for all good men" into "Now is the time for..."
  *
  * Specifically:
*
    *
  • If str is less than maxWidth characters * long, return it.
  • *
  • Else abbreviate it to (substring(str, 0, max-3) + "...").
  • *
  • If maxWidth is less than 4, throw an * IllegalArgumentException.
  • *
  • In no case will it return a String of length greater than * maxWidth.
  • *
  * 
  *
*
   * StringUtils.abbreviate(null, *)      = null
   * StringUtils.abbreviate("", 4)        = ""
   * StringUtils.abbreviate("abcdefg", 6) = "abc..."
   * StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
   * StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
   * StringUtils.abbreviate("abcdefg", 4) = "a..."
   * StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
   * 
  *
  * @param str  the String to check, may be null
  * @param maxWidth  maximum length of result String, must be at least 4
  * @return abbreviated String, null if null String input
  * @throws IllegalArgumentException if the width is too small
  * @since 2.0
  */
 public static String abbreviate(String str, int maxWidth) {
     return abbreviate(str, 0, maxWidth);
 }
 /**
  * Abbreviates a String using ellipses. This will turn
  * "Now is the time for all good men" into "...is the time for..."
  *
  * Works like abbreviate(String, int), but allows you to specify
  * a "left edge" offset.  Note that this left edge is not necessarily going to
  * be the leftmost character in the result, or the first character following the
  * ellipses, but it will appear somewhere in the result.
  *
  * In no case will it return a String of length greater than
  * maxWidth.
  *
*
   * StringUtils.abbreviate(null, *, *)                = null
   * StringUtils.abbreviate("", 0, 4)                  = ""
   * StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
   * StringUtils.abbreviate("abcdefghijklmno", 0, 10)  = "abcdefg..."
   * StringUtils.abbreviate("abcdefghijklmno", 1, 10)  = "abcdefg..."
   * StringUtils.abbreviate("abcdefghijklmno", 4, 10)  = "abcdefg..."
   * StringUtils.abbreviate("abcdefghijklmno", 5, 10)  = "...fghi..."
   * StringUtils.abbreviate("abcdefghijklmno", 6, 10)  = "...ghij..."
   * StringUtils.abbreviate("abcdefghijklmno", 8, 10)  = "...ijklmno"
   * StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
   * StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
   * StringUtils.abbreviate("abcdefghij", 0, 3)        = IllegalArgumentException
   * StringUtils.abbreviate("abcdefghij", 5, 6)        = IllegalArgumentException
   * 
  *
  * @param str  the String to check, may be null
  * @param offset  left edge of source String
  * @param maxWidth  maximum length of result String, must be at least 4
  * @return abbreviated String, null if null String input
  * @throws IllegalArgumentException if the width is too small
  * @since 2.0
  */
 public static String abbreviate(String str, int offset, int maxWidth) {
     if (str == null) {
         return null;
     }
     if (maxWidth < 4) {
         throw new IllegalArgumentException("Minimum abbreviation width is 4");
     }
     if (str.length() <= maxWidth) {
         return str;
     }
     if (offset > str.length()) {
         offset = str.length();
     }
     if ((str.length() - offset) < (maxWidth - 3)) {
         offset = str.length() - (maxWidth - 3);
     }
     if (offset <= 4) {
         return str.substring(0, maxWidth - 3) + "...";
     }
     if (maxWidth < 7) {
         throw new IllegalArgumentException("Minimum abbreviation width with offset is 7");
     }
     if ((offset + (maxWidth - 3)) < str.length()) {
         return "..." + abbreviate(str.substring(offset), maxWidth - 3);
     }
     return "..." + str.substring(str.length() - (maxWidth - 3));
 }

}</source>





Abbreviate string

   <source lang="java">

/**

* $Revision: 10205 $
* $Date: 2008-04-11 15:48:27 -0700 (Fri, 11 Apr 2008) $
*
* Copyright (C) 2004-2008 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution, or a commercial license
* agreement with Jive.
*/

import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.BreakIterator; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /**

* Utility class to peform common String manipulation algorithms.
*/

public class StringUtils {

   // Constants used by escapeHTMLTags
   private static final char[] QUOTE_ENCODE = """.toCharArray();
   private static final char[] AMP_ENCODE = "&".toCharArray();
   private static final char[] LT_ENCODE = "<".toCharArray();
   private static final char[] GT_ENCODE = ">".toCharArray();
   private StringUtils() {
       // Not instantiable.
   }
   /**
    * Abbreviates a string to a specified length and then adds an ellipsis
    * if the input is greater than the maxWidth. Example input:
*
     *      user1@jivesoftware.ru/home
     * 
    * and a maximum length of 20 characters, the abbreviate method will return:
*
     *      user1@jivesoftware.c...
     * 
    * @param str the String to abbreviate.
    * @param maxWidth the maximum size of the string, minus the ellipsis.
    * @return the abbreviated String, or null if the string was null.
    */
   public static String abbreviate(String str, int maxWidth) {
       if (null == str) {
           return null;
       }
       if (str.length() <= maxWidth) {
           return str;
       }
       
       return str.substring(0, maxWidth) + "...";
   }

}</source>





Capital and uncapital strings

   <source lang="java">

/* ------------------------------------------------------------------------

* $Id: StringUtil.java,v 1.1 2005/12/26 12:59:25 tpv Exp $
* Copyright 2005 Tim Vernum
* ------------------------------------------------------------------------
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ------------------------------------------------------------------------
*/

/**

* @version $Revision: 1.1 $
*/

public final class StringUtil {

   private StringUtil()
   {
       // Static utility class
   }
   public static String uncaps(String string)
   {
       if (string.length() == 0)
       {
           return string;
       }
       char ch = string.charAt(0);
       if (Character.isUpperCase(ch))
       {
           ch = Character.toLowerCase(ch);
           return ch + string.substring(1);
       }
       return string;
   }
   public static String caps(String string)
   {
       if (string.length() == 0)
       {
           return string;
       }
       char ch = string.charAt(0);
       if (Character.isLowerCase(ch))
       {
           ch = Character.toUpperCase(ch);
           return ch + string.substring(1);
       }
       return string;
   }
   public static boolean isBlank(String value)
   {
       return value == null || value.length() == 0;
   }
   public static boolean isBlankOrSpace(String value)
   {
       return isBlank(value) || isBlank(value.trim());
   }

}</source>





Capitalize the first character of the given string

   <source lang="java">

import java.util.Map;

/*

 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

public class Main{

 /**
  * Capitalize the first character of the given string.
  *
  * @param string     String to capitalize.
  * @return           Capitalized string.
  *
  * @throws IllegalArgumentException    String is <kk>null</kk> or empty.
  */
 public static String capitalize(final String string)
 {
    if (string == null)
       throw new NullPointerException("string");
    if (string.equals(""))
       throw new NullPointerException("string");
    return Character.toUpperCase(string.charAt(0)) + string.substring(1);
 }

}</source>





Centers a String in a larger String of size size. Uses a supplied character as the value to pad the String with.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  See the NOTICE file distributed with
*  this work for additional information regarding copyright ownership.
*  The ASF licenses this file to You under the Apache License, Version 2.0
*  (the "License"); you may not use this file except in compliance with
*  the License.  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*
*/

public class Main {

 /**
  * The maximum size to which the padding constant(s) can expand.
  */
 private static final int PAD_LIMIT = 8192;
 /**
  * Centers a String in a larger String of size size.
  * Uses a supplied character as the value to pad the String with.
  *
  * If the size is less than the String length, the String is returned.
  * A null String returns null.
  * A negative size is treated as zero.
  *
*
   * StringUtils.center(null, *, *)     = null
   * StringUtils.center("", 4, " ")     = "    "
   * StringUtils.center("ab", -1, " ")  = "ab"
   * StringUtils.center("ab", 4, " ")   = " ab"
   * StringUtils.center("abcd", 2, " ") = "abcd"
   * StringUtils.center("a", 4, " ")    = " a  "
   * StringUtils.center("a", 4, "y")    = "yayy"
   * 
  *
  * @param str  the String to center, may be null
  * @param size  the int size of new String, negative treated as zero
  * @param padChar  the character to pad the new String with
  * @return centered String, null if null String input
  * @since 2.0
  */
 public static String center(String str, int size, char padChar) {
     if (str == null || size <= 0) {
         return str;
     }
     int strLen = str.length();
     int pads = size - strLen;
     if (pads <= 0) {
         return str;
     }
     str = leftPad(str, strLen + pads / 2, padChar);
     str = rightPad(str, size, padChar);
     return str;
 }
 /**
  * Centers a String in a larger String of size size.
  * Uses a supplied String as the value to pad the String with.
  *
  * If the size is less than the String length, the String is returned.
  * A null String returns null.
  * A negative size is treated as zero.
  *
*
   * StringUtils.center(null, *, *)     = null
   * StringUtils.center("", 4, " ")     = "    "
   * StringUtils.center("ab", -1, " ")  = "ab"
   * StringUtils.center("ab", 4, " ")   = " ab"
   * StringUtils.center("abcd", 2, " ") = "abcd"
   * StringUtils.center("a", 4, " ")    = " a  "
   * StringUtils.center("a", 4, "yz")   = "yayz"
   * StringUtils.center("abc", 7, null) = "  abc  "
   * StringUtils.center("abc", 7, "")   = "  abc  "
   * 
  *
  * @param str  the String to center, may be null
  * @param size  the int size of new String, negative treated as zero
  * @param padStr  the String to pad the new String with, must not be null or empty
  * @return centered String, null if null String input
  * @throws IllegalArgumentException if padStr is null or empty
  */
 public static String center(String str, int size, String padStr) {
     if (str == null || size <= 0) {
         return str;
     }
     if (isEmpty(padStr)) {
         padStr = " ";
     }
     int strLen = str.length();
     int pads = size - strLen;
     if (pads <= 0) {
         return str;
     }
     str = leftPad(str, strLen + pads / 2, padStr);
     str = rightPad(str, size, padStr);
     return str;
 }
 /**
  * Right pad a String with a specified character.
  *
  * The String is padded to the size of size.
  *
*
   * StringUtils.rightPad(null, *, *)     = null
   * StringUtils.rightPad("", 3, "z")     = "zzz"
   * StringUtils.rightPad("bat", 3, "z")  = "bat"
   * StringUtils.rightPad("bat", 5, "z")  = "batzz"
   * StringUtils.rightPad("bat", 1, "z")  = "bat"
   * StringUtils.rightPad("bat", -1, "z") = "bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padChar  the character to pad with
  * @return right padded String or original String if no padding is necessary,
  *  null if null String input
  * @since 2.0
  */
 public static String rightPad(String str, int size, char padChar) {
     if (str == null) {
         return null;
     }
     int pads = size - str.length();
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (pads > PAD_LIMIT) {
         return rightPad(str, size, String.valueOf(padChar));
     }
     return str.concat(padding(pads, padChar));
 }
 /**
  * Right pad a String with a specified String.
  *
  * The String is padded to the size of size.
  *
*
   * StringUtils.rightPad(null, *, *)      = null
   * StringUtils.rightPad("", 3, "z")      = "zzz"
   * StringUtils.rightPad("bat", 3, "yz")  = "bat"
   * StringUtils.rightPad("bat", 5, "yz")  = "batyz"
   * StringUtils.rightPad("bat", 8, "yz")  = "batyzyzy"
   * StringUtils.rightPad("bat", 1, "yz")  = "bat"
   * StringUtils.rightPad("bat", -1, "yz") = "bat"
   * StringUtils.rightPad("bat", 5, null)  = "bat  "
   * StringUtils.rightPad("bat", 5, "")    = "bat  "
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padStr  the String to pad with, null or empty treated as single space
  * @return right padded String or original String if no padding is necessary,
  *  null if null String input
  */
 public static String rightPad(String str, int size, String padStr) {
     if (str == null) {
         return null;
     }
     if (isEmpty(padStr)) {
         padStr = " ";
     }
     int padLen = padStr.length();
     int strLen = str.length();
     int pads = size - strLen;
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (padLen == 1 && pads <= PAD_LIMIT) {
         return rightPad(str, size, padStr.charAt(0));
     }
     if (pads == padLen) {
         return str.concat(padStr);
     } else if (pads < padLen) {
         return str.concat(padStr.substring(0, pads));
     } else {
         char[] padding = new char[pads];
         char[] padChars = padStr.toCharArray();
         for (int i = 0; i < pads; i++) {
             padding[i] = padChars[i % padLen];
         }
         return str.concat(new String(padding));
     }
 }
 /**
  * Left pad a String with a specified character.
  *
  * Pad to a size of size.
  *
*
   * StringUtils.leftPad(null, *, *)     = null
   * StringUtils.leftPad("", 3, "z")     = "zzz"
   * StringUtils.leftPad("bat", 3, "z")  = "bat"
   * StringUtils.leftPad("bat", 5, "z")  = "zzbat"
   * StringUtils.leftPad("bat", 1, "z")  = "bat"
   * StringUtils.leftPad("bat", -1, "z") = "bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padChar  the character to pad with
  * @return left padded String or original String if no padding is necessary,
  *  null if null String input
  * @since 2.0
  */
 public static String leftPad(String str, int size, char padChar) {
     if (str == null) {
         return null;
     }
     int pads = size - str.length();
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (pads > PAD_LIMIT) {
         return leftPad(str, size, String.valueOf(padChar));
     }
     return padding(pads, padChar).concat(str);
 }
 /**
  * Left pad a String with a specified String.
  *
  * Pad to a size of size.
  *
*
   * StringUtils.leftPad(null, *, *)      = null
   * StringUtils.leftPad("", 3, "z")      = "zzz"
   * StringUtils.leftPad("bat", 3, "yz")  = "bat"
   * StringUtils.leftPad("bat", 5, "yz")  = "yzbat"
   * StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat"
   * StringUtils.leftPad("bat", 1, "yz")  = "bat"
   * StringUtils.leftPad("bat", -1, "yz") = "bat"
   * StringUtils.leftPad("bat", 5, null)  = "  bat"
   * StringUtils.leftPad("bat", 5, "")    = "  bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padStr  the String to pad with, null or empty treated as single space
  * @return left padded String or original String if no padding is necessary,
  *  null if null String input
  */
 public static String leftPad(String str, int size, String padStr) {
     if (str == null) {
         return null;
     }
     if (isEmpty(padStr)) {
         padStr = " ";
     }
     int padLen = padStr.length();
     int strLen = str.length();
     int pads = size - strLen;
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (padLen == 1 && pads <= PAD_LIMIT) {
         return leftPad(str, size, padStr.charAt(0));
     }
     if (pads == padLen) {
         return padStr.concat(str);
     } else if (pads < padLen) {
         return padStr.substring(0, pads).concat(str);
     } else {
         char[] padding = new char[pads];
         char[] padChars = padStr.toCharArray();
         for (int i = 0; i < pads; i++) {
             padding[i] = padChars[i % padLen];
         }
         return new String(padding).concat(str);
     }
 }
 /**
  * Returns padding using the specified delimiter repeated
  * to a given length.
  *
*
   * StringUtils.padding(0, "e")  = ""
   * StringUtils.padding(3, "e")  = "eee"
   * StringUtils.padding(-2, "e") = IndexOutOfBoundsException
   * 
  *
  * Note: this method doesn"t not support padding with
  * 
  * as they require a pair of chars to be represented.
  * If you are needing to support full I18N of your applications
  * consider using {@link #repeat(String, int)} instead. 
  * 
  *
  * @param repeat  number of times to repeat delim
  * @param padChar  character to repeat
  * @return String with repeated character
  * @throws IndexOutOfBoundsException if repeat < 0
  * @see #repeat(String, int)
  */
 private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException {
     if (repeat < 0) {
         throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat);
     }
     final char[] buf = new char[repeat];
     for (int i = 0; i < buf.length; i++) {
         buf[i] = padChar;
     }
     return new String(buf);
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
  * Checks if a String is empty ("") or null.
  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
  * NOTE: This method changed in Lang version 2.0.
  * It no longer trims the String.
  * That functionality is available in isBlank().
  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}</source>





Centers a String in a larger String of size size. Uses a supplied String as the value to pad the String with.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  See the NOTICE file distributed with
*  this work for additional information regarding copyright ownership.
*  The ASF licenses this file to You under the Apache License, Version 2.0
*  (the "License"); you may not use this file except in compliance with
*  the License.  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*
*/

public class Main {

 /**
  * The maximum size to which the padding constant(s) can expand.
  */
 private static final int PAD_LIMIT = 8192;
 /**
  * Centers a String in a larger String of size size.
  * Uses a supplied String as the value to pad the String with.
  *
  * If the size is less than the String length, the String is returned.
  * A null String returns null.
  * A negative size is treated as zero.
  *
*
   * StringUtils.center(null, *, *)     = null
   * StringUtils.center("", 4, " ")     = "    "
   * StringUtils.center("ab", -1, " ")  = "ab"
   * StringUtils.center("ab", 4, " ")   = " ab"
   * StringUtils.center("abcd", 2, " ") = "abcd"
   * StringUtils.center("a", 4, " ")    = " a  "
   * StringUtils.center("a", 4, "yz")   = "yayz"
   * StringUtils.center("abc", 7, null) = "  abc  "
   * StringUtils.center("abc", 7, "")   = "  abc  "
   * 
  *
  * @param str  the String to center, may be null
  * @param size  the int size of new String, negative treated as zero
  * @param padStr  the String to pad the new String with, must not be null or empty
  * @return centered String, null if null String input
  * @throws IllegalArgumentException if padStr is null or empty
  */
 public static String center(String str, int size, String padStr) {
     if (str == null || size <= 0) {
         return str;
     }
     if (isEmpty(padStr)) {
         padStr = " ";
     }
     int strLen = str.length();
     int pads = size - strLen;
     if (pads <= 0) {
         return str;
     }
     str = leftPad(str, strLen + pads / 2, padStr);
     str = rightPad(str, size, padStr);
     return str;
 }
 /**
  * Right pad a String with a specified character.
  *
  * The String is padded to the size of size.
  *
*
   * StringUtils.rightPad(null, *, *)     = null
   * StringUtils.rightPad("", 3, "z")     = "zzz"
   * StringUtils.rightPad("bat", 3, "z")  = "bat"
   * StringUtils.rightPad("bat", 5, "z")  = "batzz"
   * StringUtils.rightPad("bat", 1, "z")  = "bat"
   * StringUtils.rightPad("bat", -1, "z") = "bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padChar  the character to pad with
  * @return right padded String or original String if no padding is necessary,
  *  null if null String input
  * @since 2.0
  */
 public static String rightPad(String str, int size, char padChar) {
     if (str == null) {
         return null;
     }
     int pads = size - str.length();
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (pads > PAD_LIMIT) {
         return rightPad(str, size, String.valueOf(padChar));
     }
     return str.concat(padding(pads, padChar));
 }
 /**
  * Right pad a String with a specified String.
  *
  * The String is padded to the size of size.
  *
*
   * StringUtils.rightPad(null, *, *)      = null
   * StringUtils.rightPad("", 3, "z")      = "zzz"
   * StringUtils.rightPad("bat", 3, "yz")  = "bat"
   * StringUtils.rightPad("bat", 5, "yz")  = "batyz"
   * StringUtils.rightPad("bat", 8, "yz")  = "batyzyzy"
   * StringUtils.rightPad("bat", 1, "yz")  = "bat"
   * StringUtils.rightPad("bat", -1, "yz") = "bat"
   * StringUtils.rightPad("bat", 5, null)  = "bat  "
   * StringUtils.rightPad("bat", 5, "")    = "bat  "
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padStr  the String to pad with, null or empty treated as single space
  * @return right padded String or original String if no padding is necessary,
  *  null if null String input
  */
 public static String rightPad(String str, int size, String padStr) {
     if (str == null) {
         return null;
     }
     if (isEmpty(padStr)) {
         padStr = " ";
     }
     int padLen = padStr.length();
     int strLen = str.length();
     int pads = size - strLen;
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (padLen == 1 && pads <= PAD_LIMIT) {
         return rightPad(str, size, padStr.charAt(0));
     }
     if (pads == padLen) {
         return str.concat(padStr);
     } else if (pads < padLen) {
         return str.concat(padStr.substring(0, pads));
     } else {
         char[] padding = new char[pads];
         char[] padChars = padStr.toCharArray();
         for (int i = 0; i < pads; i++) {
             padding[i] = padChars[i % padLen];
         }
         return str.concat(new String(padding));
     }
 }
 /**
  * Left pad a String with a specified character.
  *
  * Pad to a size of size.
  *
*
   * StringUtils.leftPad(null, *, *)     = null
   * StringUtils.leftPad("", 3, "z")     = "zzz"
   * StringUtils.leftPad("bat", 3, "z")  = "bat"
   * StringUtils.leftPad("bat", 5, "z")  = "zzbat"
   * StringUtils.leftPad("bat", 1, "z")  = "bat"
   * StringUtils.leftPad("bat", -1, "z") = "bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padChar  the character to pad with
  * @return left padded String or original String if no padding is necessary,
  *  null if null String input
  * @since 2.0
  */
 public static String leftPad(String str, int size, char padChar) {
     if (str == null) {
         return null;
     }
     int pads = size - str.length();
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (pads > PAD_LIMIT) {
         return leftPad(str, size, String.valueOf(padChar));
     }
     return padding(pads, padChar).concat(str);
 }
 /**
  * Left pad a String with a specified String.
  *
  * Pad to a size of size.
  *
*
   * StringUtils.leftPad(null, *, *)      = null
   * StringUtils.leftPad("", 3, "z")      = "zzz"
   * StringUtils.leftPad("bat", 3, "yz")  = "bat"
   * StringUtils.leftPad("bat", 5, "yz")  = "yzbat"
   * StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat"
   * StringUtils.leftPad("bat", 1, "yz")  = "bat"
   * StringUtils.leftPad("bat", -1, "yz") = "bat"
   * StringUtils.leftPad("bat", 5, null)  = "  bat"
   * StringUtils.leftPad("bat", 5, "")    = "  bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padStr  the String to pad with, null or empty treated as single space
  * @return left padded String or original String if no padding is necessary,
  *  null if null String input
  */
 public static String leftPad(String str, int size, String padStr) {
     if (str == null) {
         return null;
     }
     if (isEmpty(padStr)) {
         padStr = " ";
     }
     int padLen = padStr.length();
     int strLen = str.length();
     int pads = size - strLen;
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (padLen == 1 && pads <= PAD_LIMIT) {
         return leftPad(str, size, padStr.charAt(0));
     }
     if (pads == padLen) {
         return padStr.concat(str);
     } else if (pads < padLen) {
         return padStr.substring(0, pads).concat(str);
     } else {
         char[] padding = new char[pads];
         char[] padChars = padStr.toCharArray();
         for (int i = 0; i < pads; i++) {
             padding[i] = padChars[i % padLen];
         }
         return new String(padding).concat(str);
     }
 }
 /**
  * Returns padding using the specified delimiter repeated
  * to a given length.
  *
*
   * StringUtils.padding(0, "e")  = ""
   * StringUtils.padding(3, "e")  = "eee"
   * StringUtils.padding(-2, "e") = IndexOutOfBoundsException
   * 
  *
  * Note: this method doesn"t not support padding with
  * 
  * as they require a pair of chars to be represented.
  * If you are needing to support full I18N of your applications
  * consider using {@link #repeat(String, int)} instead. 
  * 
  *
  * @param repeat  number of times to repeat delim
  * @param padChar  character to repeat
  * @return String with repeated character
  * @throws IndexOutOfBoundsException if repeat < 0
  * @see #repeat(String, int)
  */
 private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException {
     if (repeat < 0) {
         throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat);
     }
     final char[] buf = new char[repeat];
     for (int i = 0; i < buf.length; i++) {
         buf[i] = padChar;
     }
     return new String(buf);
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
  * Checks if a String is empty ("") or null.
  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
  * NOTE: This method changed in Lang version 2.0.
  * It no longer trims the String.
  * That functionality is available in isBlank().
  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}</source>





Centers a String in a larger String of size size using the space character (" ").

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  See the NOTICE file distributed with
*  this work for additional information regarding copyright ownership.
*  The ASF licenses this file to You under the Apache License, Version 2.0
*  (the "License"); you may not use this file except in compliance with
*  the License.  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*
*/

public class Main {

 /**
  * The maximum size to which the padding constant(s) can expand.
  */
 private static final int PAD_LIMIT = 8192;
 
 // Centering
 //-----------------------------------------------------------------------
 /**
  * Centers a String in a larger String of size size
  * using the space character (" ").
  *
  * If the size is less than the String length, the String is returned.
  * A null String returns null.
  * A negative size is treated as zero.
  *
  * Equivalent to center(str, size, " ").
  *
*
   * StringUtils.center(null, *)   = null
   * StringUtils.center("", 4)     = "    "
   * StringUtils.center("ab", -1)  = "ab"
   * StringUtils.center("ab", 4)   = " ab "
   * StringUtils.center("abcd", 2) = "abcd"
   * StringUtils.center("a", 4)    = " a  "
   * 
  *
  * @param str  the String to center, may be null
  * @param size  the int size of new String, negative treated as zero
  * @return centered String, null if null String input
  */
 public static String center(String str, int size) {
     return center(str, size, " ");
 }
 /**
  * Centers a String in a larger String of size size.
  * Uses a supplied character as the value to pad the String with.
  *
  * If the size is less than the String length, the String is returned.
  * A null String returns null.
  * A negative size is treated as zero.
  *
*
   * StringUtils.center(null, *, *)     = null
   * StringUtils.center("", 4, " ")     = "    "
   * StringUtils.center("ab", -1, " ")  = "ab"
   * StringUtils.center("ab", 4, " ")   = " ab"
   * StringUtils.center("abcd", 2, " ") = "abcd"
   * StringUtils.center("a", 4, " ")    = " a  "
   * StringUtils.center("a", 4, "y")    = "yayy"
   * 
  *
  * @param str  the String to center, may be null
  * @param size  the int size of new String, negative treated as zero
  * @param padChar  the character to pad the new String with
  * @return centered String, null if null String input
  * @since 2.0
  */
 public static String center(String str, int size, char padChar) {
     if (str == null || size <= 0) {
         return str;
     }
     int strLen = str.length();
     int pads = size - strLen;
     if (pads <= 0) {
         return str;
     }
     str = leftPad(str, strLen + pads / 2, padChar);
     str = rightPad(str, size, padChar);
     return str;
 }
 /**
  * Centers a String in a larger String of size size.
  * Uses a supplied String as the value to pad the String with.
  *
  * If the size is less than the String length, the String is returned.
  * A null String returns null.
  * A negative size is treated as zero.
  *
*
   * StringUtils.center(null, *, *)     = null
   * StringUtils.center("", 4, " ")     = "    "
   * StringUtils.center("ab", -1, " ")  = "ab"
   * StringUtils.center("ab", 4, " ")   = " ab"
   * StringUtils.center("abcd", 2, " ") = "abcd"
   * StringUtils.center("a", 4, " ")    = " a  "
   * StringUtils.center("a", 4, "yz")   = "yayz"
   * StringUtils.center("abc", 7, null) = "  abc  "
   * StringUtils.center("abc", 7, "")   = "  abc  "
   * 
  *
  * @param str  the String to center, may be null
  * @param size  the int size of new String, negative treated as zero
  * @param padStr  the String to pad the new String with, must not be null or empty
  * @return centered String, null if null String input
  * @throws IllegalArgumentException if padStr is null or empty
  */
 public static String center(String str, int size, String padStr) {
     if (str == null || size <= 0) {
         return str;
     }
     if (isEmpty(padStr)) {
         padStr = " ";
     }
     int strLen = str.length();
     int pads = size - strLen;
     if (pads <= 0) {
         return str;
     }
     str = leftPad(str, strLen + pads / 2, padStr);
     str = rightPad(str, size, padStr);
     return str;
 }
 /**
  * Right pad a String with a specified character.
  *
  * The String is padded to the size of size.
  *
*
   * StringUtils.rightPad(null, *, *)     = null
   * StringUtils.rightPad("", 3, "z")     = "zzz"
   * StringUtils.rightPad("bat", 3, "z")  = "bat"
   * StringUtils.rightPad("bat", 5, "z")  = "batzz"
   * StringUtils.rightPad("bat", 1, "z")  = "bat"
   * StringUtils.rightPad("bat", -1, "z") = "bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padChar  the character to pad with
  * @return right padded String or original String if no padding is necessary,
  *  null if null String input
  * @since 2.0
  */
 public static String rightPad(String str, int size, char padChar) {
     if (str == null) {
         return null;
     }
     int pads = size - str.length();
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (pads > PAD_LIMIT) {
         return rightPad(str, size, String.valueOf(padChar));
     }
     return str.concat(padding(pads, padChar));
 }
 /**
  * Right pad a String with a specified String.
  *
  * The String is padded to the size of size.
  *
*
   * StringUtils.rightPad(null, *, *)      = null
   * StringUtils.rightPad("", 3, "z")      = "zzz"
   * StringUtils.rightPad("bat", 3, "yz")  = "bat"
   * StringUtils.rightPad("bat", 5, "yz")  = "batyz"
   * StringUtils.rightPad("bat", 8, "yz")  = "batyzyzy"
   * StringUtils.rightPad("bat", 1, "yz")  = "bat"
   * StringUtils.rightPad("bat", -1, "yz") = "bat"
   * StringUtils.rightPad("bat", 5, null)  = "bat  "
   * StringUtils.rightPad("bat", 5, "")    = "bat  "
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padStr  the String to pad with, null or empty treated as single space
  * @return right padded String or original String if no padding is necessary,
  *  null if null String input
  */
 public static String rightPad(String str, int size, String padStr) {
     if (str == null) {
         return null;
     }
     if (isEmpty(padStr)) {
         padStr = " ";
     }
     int padLen = padStr.length();
     int strLen = str.length();
     int pads = size - strLen;
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (padLen == 1 && pads <= PAD_LIMIT) {
         return rightPad(str, size, padStr.charAt(0));
     }
     if (pads == padLen) {
         return str.concat(padStr);
     } else if (pads < padLen) {
         return str.concat(padStr.substring(0, pads));
     } else {
         char[] padding = new char[pads];
         char[] padChars = padStr.toCharArray();
         for (int i = 0; i < pads; i++) {
             padding[i] = padChars[i % padLen];
         }
         return str.concat(new String(padding));
     }
 }
 /**
  * Left pad a String with a specified character.
  *
  * Pad to a size of size.
  *
*
   * StringUtils.leftPad(null, *, *)     = null
   * StringUtils.leftPad("", 3, "z")     = "zzz"
   * StringUtils.leftPad("bat", 3, "z")  = "bat"
   * StringUtils.leftPad("bat", 5, "z")  = "zzbat"
   * StringUtils.leftPad("bat", 1, "z")  = "bat"
   * StringUtils.leftPad("bat", -1, "z") = "bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padChar  the character to pad with
  * @return left padded String or original String if no padding is necessary,
  *  null if null String input
  * @since 2.0
  */
 public static String leftPad(String str, int size, char padChar) {
     if (str == null) {
         return null;
     }
     int pads = size - str.length();
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (pads > PAD_LIMIT) {
         return leftPad(str, size, String.valueOf(padChar));
     }
     return padding(pads, padChar).concat(str);
 }
 /**
  * Left pad a String with a specified String.
  *
  * Pad to a size of size.
  *
*
   * StringUtils.leftPad(null, *, *)      = null
   * StringUtils.leftPad("", 3, "z")      = "zzz"
   * StringUtils.leftPad("bat", 3, "yz")  = "bat"
   * StringUtils.leftPad("bat", 5, "yz")  = "yzbat"
   * StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat"
   * StringUtils.leftPad("bat", 1, "yz")  = "bat"
   * StringUtils.leftPad("bat", -1, "yz") = "bat"
   * StringUtils.leftPad("bat", 5, null)  = "  bat"
   * StringUtils.leftPad("bat", 5, "")    = "  bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padStr  the String to pad with, null or empty treated as single space
  * @return left padded String or original String if no padding is necessary,
  *  null if null String input
  */
 public static String leftPad(String str, int size, String padStr) {
     if (str == null) {
         return null;
     }
     if (isEmpty(padStr)) {
         padStr = " ";
     }
     int padLen = padStr.length();
     int strLen = str.length();
     int pads = size - strLen;
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (padLen == 1 && pads <= PAD_LIMIT) {
         return leftPad(str, size, padStr.charAt(0));
     }
     if (pads == padLen) {
         return padStr.concat(str);
     } else if (pads < padLen) {
         return padStr.substring(0, pads).concat(str);
     } else {
         char[] padding = new char[pads];
         char[] padChars = padStr.toCharArray();
         for (int i = 0; i < pads; i++) {
             padding[i] = padChars[i % padLen];
         }
         return new String(padding).concat(str);
     }
 }
 /**
  * Returns padding using the specified delimiter repeated
  * to a given length.
  *
*
   * StringUtils.padding(0, "e")  = ""
   * StringUtils.padding(3, "e")  = "eee"
   * StringUtils.padding(-2, "e") = IndexOutOfBoundsException
   * 
  *
  * Note: this method doesn"t not support padding with
  * 
  * as they require a pair of chars to be represented.
  * If you are needing to support full I18N of your applications
  * consider using {@link #repeat(String, int)} instead. 
  * 
  *
  * @param repeat  number of times to repeat delim
  * @param padChar  character to repeat
  * @return String with repeated character
  * @throws IndexOutOfBoundsException if repeat < 0
  * @see #repeat(String, int)
  */
 private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException {
     if (repeat < 0) {
         throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat);
     }
     final char[] buf = new char[repeat];
     for (int i = 0; i < buf.length; i++) {
         buf[i] = padChar;
     }
     return new String(buf);
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
  * Checks if a String is empty ("") or null.
  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
  * NOTE: This method changed in Lang version 2.0.
  * It no longer trims the String.
  * That functionality is available in isBlank().
  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}</source>





Convert string to uppercase

   <source lang="java">

import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Locale; import java.util.Properties; /*

  Derby - Class org.apache.derby.iapi.util.PropertyUtil
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to you under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

public class Main {

 /** Convert string to uppercase
  * Always use the java.util.ENGLISH locale
  * @param s   string to uppercase
  * @return uppercased string
  */
 public static String SQLToUpperCase(String s)
 {
     return s.toUpperCase(Locale.ENGLISH);
 }

}</source>





Fix Line Separator

   <source lang="java">

import java.io.UnsupportedEncodingException; public class Utils {

 public static String fixLineSeparator(String xml) throws UnsupportedEncodingException {
   if ("\r\n".equals(System.getProperty("line.separator"))) {
     xml = xml.replaceAll("\r[^\n]", System.getProperty("line.separator"));
   } else {
     xml = xml.replaceAll("\r\n", System.getProperty("line.separator"));
   }
   return xml;
 }

}</source>





Format a String (JDK1.5)

   <source lang="java">

public class Main {

 public static void main(String args[]) {
   System.out.println(String.format("Hi %s at %s", "name", "your place"));
 }

} //Hi name at your place</source>





Format Calendar with String.format()

   <source lang="java">

import java.util.Calendar; public class Main {

 public static void main(String args[]) {
   Object a[] = { "String 1", "String 2", Calendar.getInstance() };
   System.out.println(String.format("Hi %1$s at %2$s ( %3$tY %3$tm %3$te )", a));
 }

} //Hi String 1 at String 2 ( 2009 03 2 )</source>





Format strings into table

   <source lang="java">

public class Main {

 public static void main(String args[]) {
   String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
   System.out.format(format, "A", "AA", "AAA");
   System.out.format(format, "B", "", "BBBBB");
   System.out.format(format, "C", "CCCCC", "CCCCCCCC");
   String ex[] = { "E", "EEEEEEEEEE", "E" };
   System.out.format(String.format(format, (Object[]) ex));
 }

} /* |A |AA |AAA | |B | |BBBBB | |C |CCCCC |CCCCCCCC | |E |EEEEEEEEEE|E |

  • /</source>





Left pad a String with a specified character.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  See the NOTICE file distributed with
*  this work for additional information regarding copyright ownership.
*  The ASF licenses this file to You under the Apache License, Version 2.0
*  (the "License"); you may not use this file except in compliance with
*  the License.  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*
*/

public class Main {

 /**
  * The maximum size to which the padding constant(s) can expand.
  */
 private static final int PAD_LIMIT = 8192;
 /**
  * Left pad a String with a specified character.
  *
  * Pad to a size of size.
  *
*
   * StringUtils.leftPad(null, *, *)     = null
   * StringUtils.leftPad("", 3, "z")     = "zzz"
   * StringUtils.leftPad("bat", 3, "z")  = "bat"
   * StringUtils.leftPad("bat", 5, "z")  = "zzbat"
   * StringUtils.leftPad("bat", 1, "z")  = "bat"
   * StringUtils.leftPad("bat", -1, "z") = "bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padChar  the character to pad with
  * @return left padded String or original String if no padding is necessary,
  *  null if null String input
  * @since 2.0
  */
 public static String leftPad(String str, int size, char padChar) {
     if (str == null) {
         return null;
     }
     int pads = size - str.length();
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (pads > PAD_LIMIT) {
         return leftPad(str, size, String.valueOf(padChar));
     }
     return padding(pads, padChar).concat(str);
 }
 /**
  * Left pad a String with a specified String.
  *
  * Pad to a size of size.
  *
*
   * StringUtils.leftPad(null, *, *)      = null
   * StringUtils.leftPad("", 3, "z")      = "zzz"
   * StringUtils.leftPad("bat", 3, "yz")  = "bat"
   * StringUtils.leftPad("bat", 5, "yz")  = "yzbat"
   * StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat"
   * StringUtils.leftPad("bat", 1, "yz")  = "bat"
   * StringUtils.leftPad("bat", -1, "yz") = "bat"
   * StringUtils.leftPad("bat", 5, null)  = "  bat"
   * StringUtils.leftPad("bat", 5, "")    = "  bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padStr  the String to pad with, null or empty treated as single space
  * @return left padded String or original String if no padding is necessary,
  *  null if null String input
  */
 public static String leftPad(String str, int size, String padStr) {
     if (str == null) {
         return null;
     }
     if (isEmpty(padStr)) {
         padStr = " ";
     }
     int padLen = padStr.length();
     int strLen = str.length();
     int pads = size - strLen;
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (padLen == 1 && pads <= PAD_LIMIT) {
         return leftPad(str, size, padStr.charAt(0));
     }
     if (pads == padLen) {
         return padStr.concat(str);
     } else if (pads < padLen) {
         return padStr.substring(0, pads).concat(str);
     } else {
         char[] padding = new char[pads];
         char[] padChars = padStr.toCharArray();
         for (int i = 0; i < pads; i++) {
             padding[i] = padChars[i % padLen];
         }
         return new String(padding).concat(str);
     }
 }
 /**
  * Returns padding using the specified delimiter repeated
  * to a given length.
  *
*
   * StringUtils.padding(0, "e")  = ""
   * StringUtils.padding(3, "e")  = "eee"
   * StringUtils.padding(-2, "e") = IndexOutOfBoundsException
   * 
  *
  * Note: this method doesn"t not support padding with
  * 
  * as they require a pair of chars to be represented.
  * If you are needing to support full I18N of your applications
  * consider using {@link #repeat(String, int)} instead. 
  * 
  *
  * @param repeat  number of times to repeat delim
  * @param padChar  character to repeat
  * @return String with repeated character
  * @throws IndexOutOfBoundsException if repeat < 0
  * @see #repeat(String, int)
  */
 private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException {
     if (repeat < 0) {
         throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat);
     }
     final char[] buf = new char[repeat];
     for (int i = 0; i < buf.length; i++) {
         buf[i] = padChar;
     }
     return new String(buf);
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
  * Checks if a String is empty ("") or null.
  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
  * NOTE: This method changed in Lang version 2.0.
  * It no longer trims the String.
  * That functionality is available in isBlank().
  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}</source>





Left pad a String with a specified String.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  See the NOTICE file distributed with
*  this work for additional information regarding copyright ownership.
*  The ASF licenses this file to You under the Apache License, Version 2.0
*  (the "License"); you may not use this file except in compliance with
*  the License.  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*
*/

public class Main {

 /**
  * The maximum size to which the padding constant(s) can expand.
  */
 private static final int PAD_LIMIT = 8192;
 /**
  * Left pad a String with a specified character.
  *
  * Pad to a size of size.
  *
*
   * StringUtils.leftPad(null, *, *)     = null
   * StringUtils.leftPad("", 3, "z")     = "zzz"
   * StringUtils.leftPad("bat", 3, "z")  = "bat"
   * StringUtils.leftPad("bat", 5, "z")  = "zzbat"
   * StringUtils.leftPad("bat", 1, "z")  = "bat"
   * StringUtils.leftPad("bat", -1, "z") = "bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padChar  the character to pad with
  * @return left padded String or original String if no padding is necessary,
  *  null if null String input
  * @since 2.0
  */
 public static String leftPad(String str, int size, char padChar) {
     if (str == null) {
         return null;
     }
     int pads = size - str.length();
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (pads > PAD_LIMIT) {
         return leftPad(str, size, String.valueOf(padChar));
     }
     return padding(pads, padChar).concat(str);
 }
 /**
  * Left pad a String with a specified String.
  *
  * Pad to a size of size.
  *
*
   * StringUtils.leftPad(null, *, *)      = null
   * StringUtils.leftPad("", 3, "z")      = "zzz"
   * StringUtils.leftPad("bat", 3, "yz")  = "bat"
   * StringUtils.leftPad("bat", 5, "yz")  = "yzbat"
   * StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat"
   * StringUtils.leftPad("bat", 1, "yz")  = "bat"
   * StringUtils.leftPad("bat", -1, "yz") = "bat"
   * StringUtils.leftPad("bat", 5, null)  = "  bat"
   * StringUtils.leftPad("bat", 5, "")    = "  bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padStr  the String to pad with, null or empty treated as single space
  * @return left padded String or original String if no padding is necessary,
  *  null if null String input
  */
 public static String leftPad(String str, int size, String padStr) {
     if (str == null) {
         return null;
     }
     if (isEmpty(padStr)) {
         padStr = " ";
     }
     int padLen = padStr.length();
     int strLen = str.length();
     int pads = size - strLen;
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (padLen == 1 && pads <= PAD_LIMIT) {
         return leftPad(str, size, padStr.charAt(0));
     }
     if (pads == padLen) {
         return padStr.concat(str);
     } else if (pads < padLen) {
         return padStr.substring(0, pads).concat(str);
     } else {
         char[] padding = new char[pads];
         char[] padChars = padStr.toCharArray();
         for (int i = 0; i < pads; i++) {
             padding[i] = padChars[i % padLen];
         }
         return new String(padding).concat(str);
     }
 }
 /**
  * Returns padding using the specified delimiter repeated
  * to a given length.
  *
*
   * StringUtils.padding(0, "e")  = ""
   * StringUtils.padding(3, "e")  = "eee"
   * StringUtils.padding(-2, "e") = IndexOutOfBoundsException
   * 
  *
  * Note: this method doesn"t not support padding with
  * 
  * as they require a pair of chars to be represented.
  * If you are needing to support full I18N of your applications
  * consider using {@link #repeat(String, int)} instead. 
  * 
  *
  * @param repeat  number of times to repeat delim
  * @param padChar  character to repeat
  * @return String with repeated character
  * @throws IndexOutOfBoundsException if repeat < 0
  * @see #repeat(String, int)
  */
 private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException {
     if (repeat < 0) {
         throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat);
     }
     final char[] buf = new char[repeat];
     for (int i = 0; i < buf.length; i++) {
         buf[i] = padChar;
     }
     return new String(buf);
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
  * Checks if a String is empty ("") or null.
  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
  * NOTE: This method changed in Lang version 2.0.
  * It no longer trims the String.
  * That functionality is available in isBlank().
  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}</source>





Left pad a String with spaces (" ").

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  See the NOTICE file distributed with
*  this work for additional information regarding copyright ownership.
*  The ASF licenses this file to You under the Apache License, Version 2.0
*  (the "License"); you may not use this file except in compliance with
*  the License.  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*
*/

public class Main {

 /**
  * The maximum size to which the padding constant(s) can expand.
  */
 private static final int PAD_LIMIT = 8192;
 /**
  * Left pad a String with spaces (" ").
  *
  * The String is padded to the size of size<code>.
  *
*
   * StringUtils.leftPad(null, *)   = null
   * StringUtils.leftPad("", 3)     = "   "
   * StringUtils.leftPad("bat", 3)  = "bat"
   * StringUtils.leftPad("bat", 5)  = "  bat"
   * StringUtils.leftPad("bat", 1)  = "bat"
   * StringUtils.leftPad("bat", -1) = "bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @return left padded String or original String if no padding is necessary,
  *  <code>null if null String input
  */
 public static String leftPad(String str, int size) {
     return leftPad(str, size, " ");
 }
 /**
  * Left pad a String with a specified character.
  *
  * Pad to a size of size.
  *
*
   * StringUtils.leftPad(null, *, *)     = null
   * StringUtils.leftPad("", 3, "z")     = "zzz"
   * StringUtils.leftPad("bat", 3, "z")  = "bat"
   * StringUtils.leftPad("bat", 5, "z")  = "zzbat"
   * StringUtils.leftPad("bat", 1, "z")  = "bat"
   * StringUtils.leftPad("bat", -1, "z") = "bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padChar  the character to pad with
  * @return left padded String or original String if no padding is necessary,
  *  null if null String input
  * @since 2.0
  */
 public static String leftPad(String str, int size, char padChar) {
     if (str == null) {
         return null;
     }
     int pads = size - str.length();
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (pads > PAD_LIMIT) {
         return leftPad(str, size, String.valueOf(padChar));
     }
     return padding(pads, padChar).concat(str);
 }
 /**
  * Left pad a String with a specified String.
  *
  * Pad to a size of size.
  *
*
   * StringUtils.leftPad(null, *, *)      = null
   * StringUtils.leftPad("", 3, "z")      = "zzz"
   * StringUtils.leftPad("bat", 3, "yz")  = "bat"
   * StringUtils.leftPad("bat", 5, "yz")  = "yzbat"
   * StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat"
   * StringUtils.leftPad("bat", 1, "yz")  = "bat"
   * StringUtils.leftPad("bat", -1, "yz") = "bat"
   * StringUtils.leftPad("bat", 5, null)  = "  bat"
   * StringUtils.leftPad("bat", 5, "")    = "  bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padStr  the String to pad with, null or empty treated as single space
  * @return left padded String or original String if no padding is necessary,
  *  null if null String input
  */
 public static String leftPad(String str, int size, String padStr) {
     if (str == null) {
         return null;
     }
     if (isEmpty(padStr)) {
         padStr = " ";
     }
     int padLen = padStr.length();
     int strLen = str.length();
     int pads = size - strLen;
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (padLen == 1 && pads <= PAD_LIMIT) {
         return leftPad(str, size, padStr.charAt(0));
     }
     if (pads == padLen) {
         return padStr.concat(str);
     } else if (pads < padLen) {
         return padStr.substring(0, pads).concat(str);
     } else {
         char[] padding = new char[pads];
         char[] padChars = padStr.toCharArray();
         for (int i = 0; i < pads; i++) {
             padding[i] = padChars[i % padLen];
         }
         return new String(padding).concat(str);
     }
 }
 /**
  * Returns padding using the specified delimiter repeated
  * to a given length.
  *
*
   * StringUtils.padding(0, "e")  = ""
   * StringUtils.padding(3, "e")  = "eee"
   * StringUtils.padding(-2, "e") = IndexOutOfBoundsException
   * 
  *
  * Note: this method doesn"t not support padding with
  * 
  * as they require a pair of chars to be represented.
  * If you are needing to support full I18N of your applications
  * consider using {@link #repeat(String, int)} instead. 
  * 
  *
  * @param repeat  number of times to repeat delim
  * @param padChar  character to repeat
  * @return String with repeated character
  * @throws IndexOutOfBoundsException if repeat < 0
  * @see #repeat(String, int)
  */
 private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException {
     if (repeat < 0) {
         throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat);
     }
     final char[] buf = new char[repeat];
     for (int i = 0; i < buf.length; i++) {
         buf[i] = padChar;
     }
     return new String(buf);
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
  * Checks if a String is empty ("") or null.
  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
  * NOTE: This method changed in Lang version 2.0.
  * It no longer trims the String.
  * That functionality is available in isBlank().
  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}</source>





Makes the first letter caps and the rest lowercase.

   <source lang="java">

public class Main {

 /**
  * 
  *  Makes the first letter caps and the rest lowercase.
  * 
  *
  * 
  *  For example fooBar becomes Foobar.
  * 
  *
  * @param data capitalize this
  * @return String
  */
 static public String firstLetterCaps ( String data )
 {
     String firstLetter = data.substring(0,1).toUpperCase();
     String restLetters = data.substring(1).toLowerCase();
     return firstLetter + restLetters;
 }

}</source>





Pass value array to String.format()

   <source lang="java">

public class Main {

 public static void main(String args[]) {
   System.out.printf("Hi %s at %s", "value", "value 2");
   String a[] = { "value 1", "value 2" };
   System.out.println(String.format("hi %s at %s", a));
 }

}</source>





Put quotes around the given String if necessary.

   <source lang="java">

import java.io.File; /*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  See the NOTICE file distributed with
*  this work for additional information regarding copyright ownership.
*  The ASF licenses this file to You under the Apache License, Version 2.0
*  (the "License"); you may not use this file except in compliance with
*  the License.  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*@author 
*/

public class Main {

 private static final String SINGLE_QUOTE = "\"";
 private static final String DOUBLE_QUOTE = "\"";
 private static final char SLASH_CHAR = "/";
 private static final char BACKSLASH_CHAR = "\\";

 /**
  * Put quotes around the given String if necessary.
  * 
  * If the argument doesn"t include spaces or quotes, return it as is. If it
  * contains double quotes, use single quotes - else surround the argument by
  * double quotes.
  * 
  *
  * @param argument the argument to be quoted
  * @return the quoted argument
  * @throws IllegalArgumentException If argument contains both types of quotes
  */
 public static String quoteArgument(final String argument) {
     String cleanedArgument = argument.trim();
     while(cleanedArgument.startsWith(SINGLE_QUOTE) || cleanedArgument.startsWith(DOUBLE_QUOTE)) {
         cleanedArgument = cleanedArgument.substring(1);
     }
     while(cleanedArgument.endsWith(SINGLE_QUOTE) || cleanedArgument.endsWith(DOUBLE_QUOTE)) {
         cleanedArgument = cleanedArgument.substring(0, cleanedArgument.length() - 1);
     }
     final StringBuffer buf = new StringBuffer();
     if (cleanedArgument.indexOf(DOUBLE_QUOTE) > -1) {
         if (cleanedArgument.indexOf(SINGLE_QUOTE) > -1) {
             throw new IllegalArgumentException(
                     "Can"t handle single and double quotes in same argument");
         } else {
             return buf.append(SINGLE_QUOTE).append(cleanedArgument).append(
                     SINGLE_QUOTE).toString();
         }
     } else if (cleanedArgument.indexOf(SINGLE_QUOTE) > -1
             || cleanedArgument.indexOf(" ") > -1) {
         return buf.append(DOUBLE_QUOTE).append(cleanedArgument).append(
                 DOUBLE_QUOTE).toString();
     } else {
         return cleanedArgument;
     }
 }

}</source>





Quote a string so that it can be used as an identifier or a string literal in SQL statements.

   <source lang="java">

import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Properties; /*

  Derby - Class org.apache.derby.iapi.util.PropertyUtil
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to you under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at
     http://www.apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

public class Main {

 /**
  * Quote a string so that it can be used as an identifier or a string
  * literal in SQL statements. Identifiers are surrounded by double quotes
  * and string literals are surrounded by single quotes. If the string
  * contains quote characters, they are escaped.
  *
  * @param source the string to quote
  * @param quote the character to quote the string with (" or ")
  * @return a string quoted with the specified quote character
  * @see #quoteStringLiteral(String)
  * @see IdUtil#normalToDelimited(String)
  */
 static String quoteString(String source, char quote) {
     // Normally, the quoted string is two characters longer than the source
     // string (because of start quote and end quote).
     StringBuffer quoted = new StringBuffer(source.length() + 2);
     quoted.append(quote);
     for (int i = 0; i < source.length(); i++) {
         char c = source.charAt(i);
         // if the character is a quote, escape it with an extra quote
         if (c == quote) quoted.append(quote);
         quoted.append(c);
     }
     quoted.append(quote);
     return quoted.toString();
 }
 /**
  * Quote a string so that it can be used as a string literal in an
  * SQL statement.
  *
  * @param string the string to quote
  * @return the string surrounded by single quotes and with proper escaping
  * of any single quotes inside the string
  */
 public static String quoteStringLiteral(String string) {
     return quoteString(string, "\"");
 }

}</source>





Remove/collapse multiple newline characters.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.    
*/

/**

*
*  @author 
*  @version $Id: StringUtils.java 685685 2008-08-13 21:43:27Z nbubna $
*/

public class Main {

 /**
  * Remove/collapse multiple newline characters.
  *
  * @param argStr string to collapse newlines in.
  * @return String
  */
 public static String collapseNewlines(String argStr)
 {
     char last = argStr.charAt(0);
     StringBuffer argBuf = new StringBuffer();
     for (int cIdx = 0 ; cIdx < argStr.length(); cIdx++)
     {
         char ch = argStr.charAt(cIdx);
         if (ch != "\n" || last != "\n")
         {
             argBuf.append(ch);
             last = ch;
         }
     }
     return argBuf.toString();
 }

}</source>





Removes newline, carriage return and tab characters from a string

   <source lang="java">

/**************************************************************************************

* Copyright (c) Jonas Bon�r, Alexandre Vasseur. All rights reserved.                 *
* http://aspectwerkz.codehaus.org                                                    *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the LGPL license      *
* a copy of which has been included with this distribution in the license.txt file.  *
**************************************************************************************/

import java.util.List; import java.util.ArrayList; /**

* Utility methods for strings.
*
* @author 
*/

public class Strings {

   /**
    * Removes newline, carriage return and tab characters from a string.
    *
    * @param toBeEscaped string to escape
    * @return the escaped string
    */
   public static String removeFormattingCharacters(final String toBeEscaped) {
       StringBuffer escapedBuffer = new StringBuffer();
       for (int i = 0; i < toBeEscaped.length(); i++) {
           if ((toBeEscaped.charAt(i) != "\n") && (toBeEscaped.charAt(i) != "\r") && (toBeEscaped.charAt(i) != "\t")) {
               escapedBuffer.append(toBeEscaped.charAt(i));
           }
       }
       String s = escapedBuffer.toString();
       return s;//
       // Strings.replaceSubString(s, "\"", "")
   }
  

}</source>





Removes one newline from end of a String if it"s there, otherwise leave it alone.

   <source lang="java">

import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; /*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  See the NOTICE file distributed with
*  this work for additional information regarding copyright ownership.
*  The ASF licenses this file to You under the Apache License, Version 2.0
*  (the "License"); you may not use this file except in compliance with
*  the License.  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*
*/

public class Main {

 /**
  * \u000a linefeed LF ("\n").
  * 
  * @see 
  * @since 2.2
  */
 public static final char CR = "\r";
 /**
  * Removes one newline from end of a String if it"s there,
  * otherwise leave it alone.  A newline is "\n",
  * "\r", or "\r\n".
  *
  * NOTE: This method changed in 2.0.
  * It now more closely matches Perl chomp.
  *
*
   * StringUtils.chomp(null)          = null
   * StringUtils.chomp("")            = ""
   * StringUtils.chomp("abc \r")      = "abc "
   * StringUtils.chomp("abc\n")       = "abc"
   * StringUtils.chomp("abc\r\n")     = "abc"
   * StringUtils.chomp("abc\r\n\r\n") = "abc\r\n"
   * StringUtils.chomp("abc\n\r")     = "abc\n"
   * StringUtils.chomp("abc\n\rabc")  = "abc\n\rabc"
   * StringUtils.chomp("\r")          = ""
   * StringUtils.chomp("\n")          = ""
   * StringUtils.chomp("\r\n")        = ""
   * 
  *
  * @param str  the String to chomp a newline from, may be null
  * @return String without newline, null if null String input
  */
 public static String chomp(String str) {
     if (isEmpty(str)) {
         return str;
     }
     if (str.length() == 1) {
         char ch = str.charAt(0);
         if (ch == CR || ch == LF) {
             return "";
         }
         return str;
     }
     int lastIdx = str.length() - 1;
     char last = str.charAt(lastIdx);
     if (last == LF) {
         if (str.charAt(lastIdx - 1) == CR) {
             lastIdx--;
         }
     } else if (last != CR) {
         lastIdx++;
     }
     return str.substring(0, lastIdx);
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
  * Checks if a String is empty ("") or null.
  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
  * NOTE: This method changed in Lang version 2.0.
  * It no longer trims the String.
  * That functionality is available in isBlank().
  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}</source>





Remove the leading and trailing quotes from str.

   <source lang="java">

/**

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**

* Contains useful helper methods for classes within this package.
*
* @author John Keyes (john at integralsource.ru)
* @version $Revision: 680644 $, $Date: 2008-07-29 01:13:48 -0700 (Tue, 29 Jul 2008) $
*/

public class Main {

 /**
  * Remove the leading and trailing quotes from str.
  * E.g. if str is ""one two"", then "one two" is returned.
  *
  * @param str The string from which the leading and trailing quotes
  * should be removed.
  *
  * @return The string without the leading and trailing quotes.
  */
 static String stripLeadingAndTrailingQuotes(String str)
 {
     if (str.startsWith("\""))
     {
         str = str.substring(1, str.length());
     }
     if (str.endsWith("\""))
     {
         str = str.substring(0, str.length() - 1);
     }
     return str;
 }

}</source>





Repeat a String repeat times to form a new String.

   <source lang="java">

import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; /*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  See the NOTICE file distributed with
*  this work for additional information regarding copyright ownership.
*  The ASF licenses this file to You under the Apache License, Version 2.0
*  (the "License"); you may not use this file except in compliance with
*  the License.  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*
*/

public class Main {

 /**
  * The maximum size to which the padding constant(s) can expand.
  */
 private static final int PAD_LIMIT = 8192;
 // Padding
 //-----------------------------------------------------------------------
 /**
  * Repeat a String repeat times to form a
  * new String.
  *
*
   * StringUtils.repeat(null, 2) = null
   * StringUtils.repeat("", 0)   = ""
   * StringUtils.repeat("", 2)   = ""
   * StringUtils.repeat("a", 3)  = "aaa"
   * StringUtils.repeat("ab", 2) = "abab"
   * StringUtils.repeat("a", -2) = ""
   * 
  *
  * @param str  the String to repeat, may be null
  * @param repeat  number of times to repeat str, negative treated as zero
  * @return a new String consisting of the original String repeated,
  *  null if null String input
  */
 public static String repeat(String str, int repeat) {
     // Performance tuned for 2.0 (JDK1.4)
     if (str == null) {
         return null;
     }
     if (repeat <= 0) {
         return "";
     }
     int inputLength = str.length();
     if (repeat == 1 || inputLength == 0) {
         return str;
     }
     if (inputLength == 1 && repeat <= PAD_LIMIT) {
         return padding(repeat, str.charAt(0));
     }
     int outputLength = inputLength * repeat;
     switch (inputLength) {
         case 1 :
             char ch = str.charAt(0);
             char[] output1 = new char[outputLength];
             for (int i = repeat - 1; i >= 0; i--) {
                 output1[i] = ch;
             }
             return new String(output1);
         case 2 :
             char ch0 = str.charAt(0);
             char ch1 = str.charAt(1);
             char[] output2 = new char[outputLength];
             for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
                 output2[i] = ch0;
                 output2[i + 1] = ch1;
             }
             return new String(output2);
         default :
             StringBuffer buf = new StringBuffer(outputLength);
             for (int i = 0; i < repeat; i++) {
                 buf.append(str);
             }
             return buf.toString();
     }
 }
 /**
  * Returns padding using the specified delimiter repeated
  * to a given length.
  *
*
   * StringUtils.padding(0, "e")  = ""
   * StringUtils.padding(3, "e")  = "eee"
   * StringUtils.padding(-2, "e") = IndexOutOfBoundsException
   * 
  *
  * Note: this method doesn"t not support padding with
  * 
  * as they require a pair of chars to be represented.
  * If you are needing to support full I18N of your applications
  * consider using {@link #repeat(String, int)} instead. 
  * 
  *
  * @param repeat  number of times to repeat delim
  * @param padChar  character to repeat
  * @return String with repeated character
  * @throws IndexOutOfBoundsException if repeat < 0
  * @see #repeat(String, int)
  */
 private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException {
     if (repeat < 0) {
         throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat);
     }
     final char[] buf = new char[repeat];
     for (int i = 0; i < buf.length; i++) {
         buf[i] = padChar;
     }
     return new String(buf);
 }

}</source>





Repeat String

   <source lang="java">

/*

   JSPWiki - a JSP-based WikiWiki clone.
   Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
   distributed with this work for additional information
   regarding copyright ownership.  The ASF licenses this file
   to you under the Apache License, Version 2.0 (the
   "License"); you may not use this file except in compliance
   with the License.  You may obtain a copy of the License at
      http://www.apache.org/licenses/LICENSE-2.0
   Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an
   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   KIND, either express or implied.  See the License for the
   specific language governing permissions and limitations
   under the License.    
*/

import java.security.SecureRandom; import java.util.Random; public class StringUtils {

 /**
  *  A simple routine which just repeates the arguments.  This is useful
  *  for creating something like a line or something.
  *
  *  @param what String to repeat
  *  @param times How many times to repeat the string.
  *  @return Guess what?
  *  @since 2.1.98.
  */
 public static String repeatString( String what, int times )
 {
     StringBuffer sb = new StringBuffer();
     for( int i = 0; i < times; i++ )
     {
         sb.append( what );
     }
     return sb.toString();
 }

}</source>





Replace New Lines

   <source lang="java">

/*

* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://wingsframework.org).
*
* wingS is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* Please see COPYING for the complete licence.
*/

import java.util.StringTokenizer; /**

* Some string manipulation utilities.
*
* @author 
*/

public class StringUtil {

 /**
  * replaces all newlines in the given String "s" with the replacement
  * string "r". Each line is trimmed from leading and trailing whitespaces,
  * then the new line-delimiter is added.
  *
  * @param s the source string.
  * @param r the new line delimiter
  * @return the resulting string.
  */
 public static final String replaceNewLines(String s, String r) {
     StringBuilder result = new StringBuilder();
     StringTokenizer t = new StringTokenizer(s, "\n");
     while (t.hasMoreTokens()) {
         result.append(t.nextToken().trim()).append(r);
     }
     return result.toString();
 }
 

}</source>





Right pad a String with a specified character.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  See the NOTICE file distributed with
*  this work for additional information regarding copyright ownership.
*  The ASF licenses this file to You under the Apache License, Version 2.0
*  (the "License"); you may not use this file except in compliance with
*  the License.  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*
*/

public class Main {

 /**
  * The maximum size to which the padding constant(s) can expand.
  */
 private static final int PAD_LIMIT = 8192;
 /**
  * Right pad a String with a specified character.
  *
  * The String is padded to the size of size.
  *
*
   * StringUtils.rightPad(null, *, *)     = null
   * StringUtils.rightPad("", 3, "z")     = "zzz"
   * StringUtils.rightPad("bat", 3, "z")  = "bat"
   * StringUtils.rightPad("bat", 5, "z")  = "batzz"
   * StringUtils.rightPad("bat", 1, "z")  = "bat"
   * StringUtils.rightPad("bat", -1, "z") = "bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padChar  the character to pad with
  * @return right padded String or original String if no padding is necessary,
  *  null if null String input
  * @since 2.0
  */
 public static String rightPad(String str, int size, char padChar) {
     if (str == null) {
         return null;
     }
     int pads = size - str.length();
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (pads > PAD_LIMIT) {
         return rightPad(str, size, String.valueOf(padChar));
     }
     return str.concat(padding(pads, padChar));
 }
 /**
  * Right pad a String with a specified String.
  *
  * The String is padded to the size of size.
  *
*
   * StringUtils.rightPad(null, *, *)      = null
   * StringUtils.rightPad("", 3, "z")      = "zzz"
   * StringUtils.rightPad("bat", 3, "yz")  = "bat"
   * StringUtils.rightPad("bat", 5, "yz")  = "batyz"
   * StringUtils.rightPad("bat", 8, "yz")  = "batyzyzy"
   * StringUtils.rightPad("bat", 1, "yz")  = "bat"
   * StringUtils.rightPad("bat", -1, "yz") = "bat"
   * StringUtils.rightPad("bat", 5, null)  = "bat  "
   * StringUtils.rightPad("bat", 5, "")    = "bat  "
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padStr  the String to pad with, null or empty treated as single space
  * @return right padded String or original String if no padding is necessary,
  *  null if null String input
  */
 public static String rightPad(String str, int size, String padStr) {
     if (str == null) {
         return null;
     }
     if (isEmpty(padStr)) {
         padStr = " ";
     }
     int padLen = padStr.length();
     int strLen = str.length();
     int pads = size - strLen;
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (padLen == 1 && pads <= PAD_LIMIT) {
         return rightPad(str, size, padStr.charAt(0));
     }
     if (pads == padLen) {
         return str.concat(padStr);
     } else if (pads < padLen) {
         return str.concat(padStr.substring(0, pads));
     } else {
         char[] padding = new char[pads];
         char[] padChars = padStr.toCharArray();
         for (int i = 0; i < pads; i++) {
             padding[i] = padChars[i % padLen];
         }
         return str.concat(new String(padding));
     }
 }
 /**
  * Returns padding using the specified delimiter repeated
  * to a given length.
  *
*
   * StringUtils.padding(0, "e")  = ""
   * StringUtils.padding(3, "e")  = "eee"
   * StringUtils.padding(-2, "e") = IndexOutOfBoundsException
   * 
  *
  * Note: this method doesn"t not support padding with
  * 
  * as they require a pair of chars to be represented.
  * If you are needing to support full I18N of your applications
  * consider using {@link #repeat(String, int)} instead. 
  * 
  *
  * @param repeat  number of times to repeat delim
  * @param padChar  character to repeat
  * @return String with repeated character
  * @throws IndexOutOfBoundsException if repeat < 0
  * @see #repeat(String, int)
  */
 private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException {
     if (repeat < 0) {
         throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat);
     }
     final char[] buf = new char[repeat];
     for (int i = 0; i < buf.length; i++) {
         buf[i] = padChar;
     }
     return new String(buf);
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
  * Checks if a String is empty ("") or null.
  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
  * NOTE: This method changed in Lang version 2.0.
  * It no longer trims the String.
  * That functionality is available in isBlank().
  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}</source>





Right pad a String with a specified String.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  See the NOTICE file distributed with
*  this work for additional information regarding copyright ownership.
*  The ASF licenses this file to You under the Apache License, Version 2.0
*  (the "License"); you may not use this file except in compliance with
*  the License.  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*
*/

public class Main {

 /**
  * The maximum size to which the padding constant(s) can expand.
  */
 private static final int PAD_LIMIT = 8192;
 /**
  * Right pad a String with a specified character.
  *
  * The String is padded to the size of size.
  *
*
   * StringUtils.rightPad(null, *, *)     = null
   * StringUtils.rightPad("", 3, "z")     = "zzz"
   * StringUtils.rightPad("bat", 3, "z")  = "bat"
   * StringUtils.rightPad("bat", 5, "z")  = "batzz"
   * StringUtils.rightPad("bat", 1, "z")  = "bat"
   * StringUtils.rightPad("bat", -1, "z") = "bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padChar  the character to pad with
  * @return right padded String or original String if no padding is necessary,
  *  null if null String input
  * @since 2.0
  */
 public static String rightPad(String str, int size, char padChar) {
     if (str == null) {
         return null;
     }
     int pads = size - str.length();
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (pads > PAD_LIMIT) {
         return rightPad(str, size, String.valueOf(padChar));
     }
     return str.concat(padding(pads, padChar));
 }
 /**
  * Right pad a String with a specified String.
  *
  * The String is padded to the size of size.
  *
*
   * StringUtils.rightPad(null, *, *)      = null
   * StringUtils.rightPad("", 3, "z")      = "zzz"
   * StringUtils.rightPad("bat", 3, "yz")  = "bat"
   * StringUtils.rightPad("bat", 5, "yz")  = "batyz"
   * StringUtils.rightPad("bat", 8, "yz")  = "batyzyzy"
   * StringUtils.rightPad("bat", 1, "yz")  = "bat"
   * StringUtils.rightPad("bat", -1, "yz") = "bat"
   * StringUtils.rightPad("bat", 5, null)  = "bat  "
   * StringUtils.rightPad("bat", 5, "")    = "bat  "
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padStr  the String to pad with, null or empty treated as single space
  * @return right padded String or original String if no padding is necessary,
  *  null if null String input
  */
 public static String rightPad(String str, int size, String padStr) {
     if (str == null) {
         return null;
     }
     if (isEmpty(padStr)) {
         padStr = " ";
     }
     int padLen = padStr.length();
     int strLen = str.length();
     int pads = size - strLen;
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (padLen == 1 && pads <= PAD_LIMIT) {
         return rightPad(str, size, padStr.charAt(0));
     }
     if (pads == padLen) {
         return str.concat(padStr);
     } else if (pads < padLen) {
         return str.concat(padStr.substring(0, pads));
     } else {
         char[] padding = new char[pads];
         char[] padChars = padStr.toCharArray();
         for (int i = 0; i < pads; i++) {
             padding[i] = padChars[i % padLen];
         }
         return str.concat(new String(padding));
     }
 }
 /**
  * Returns padding using the specified delimiter repeated
  * to a given length.
  *
*
   * StringUtils.padding(0, "e")  = ""
   * StringUtils.padding(3, "e")  = "eee"
   * StringUtils.padding(-2, "e") = IndexOutOfBoundsException
   * 
  *
  * Note: this method doesn"t not support padding with
  * 
  * as they require a pair of chars to be represented.
  * If you are needing to support full I18N of your applications
  * consider using {@link #repeat(String, int)} instead. 
  * 
  *
  * @param repeat  number of times to repeat delim
  * @param padChar  character to repeat
  * @return String with repeated character
  * @throws IndexOutOfBoundsException if repeat < 0
  * @see #repeat(String, int)
  */
 private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException {
     if (repeat < 0) {
         throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat);
     }
     final char[] buf = new char[repeat];
     for (int i = 0; i < buf.length; i++) {
         buf[i] = padChar;
     }
     return new String(buf);
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
  * Checks if a String is empty ("") or null.
  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
  * NOTE: This method changed in Lang version 2.0.
  * It no longer trims the String.
  * That functionality is available in isBlank().
  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}</source>





Right pad a String with spaces (" ").

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  See the NOTICE file distributed with
*  this work for additional information regarding copyright ownership.
*  The ASF licenses this file to You under the Apache License, Version 2.0
*  (the "License"); you may not use this file except in compliance with
*  the License.  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*
*
*/

public class Main {

 /**
  * The maximum size to which the padding constant(s) can expand.
  */
 private static final int PAD_LIMIT = 8192;
 /**
  * Right pad a String with spaces (" ").
  *
  * The String is padded to the size of size.
  *
*
   * StringUtils.rightPad(null, *)   = null
   * StringUtils.rightPad("", 3)     = "   "
   * StringUtils.rightPad("bat", 3)  = "bat"
   * StringUtils.rightPad("bat", 5)  = "bat  "
   * StringUtils.rightPad("bat", 1)  = "bat"
   * StringUtils.rightPad("bat", -1) = "bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @return right padded String or original String if no padding is necessary,
  *  null if null String input
  */
 public static String rightPad(String str, int size) {
     return rightPad(str, size, " ");
 }
 /**
  * Right pad a String with a specified character.
  *
  * The String is padded to the size of size.
  *
*
   * StringUtils.rightPad(null, *, *)     = null
   * StringUtils.rightPad("", 3, "z")     = "zzz"
   * StringUtils.rightPad("bat", 3, "z")  = "bat"
   * StringUtils.rightPad("bat", 5, "z")  = "batzz"
   * StringUtils.rightPad("bat", 1, "z")  = "bat"
   * StringUtils.rightPad("bat", -1, "z") = "bat"
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padChar  the character to pad with
  * @return right padded String or original String if no padding is necessary,
  *  null if null String input
  * @since 2.0
  */
 public static String rightPad(String str, int size, char padChar) {
     if (str == null) {
         return null;
     }
     int pads = size - str.length();
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (pads > PAD_LIMIT) {
         return rightPad(str, size, String.valueOf(padChar));
     }
     return str.concat(padding(pads, padChar));
 }
 /**
  * Right pad a String with a specified String.
  *
  * The String is padded to the size of size.
  *
*
   * StringUtils.rightPad(null, *, *)      = null
   * StringUtils.rightPad("", 3, "z")      = "zzz"
   * StringUtils.rightPad("bat", 3, "yz")  = "bat"
   * StringUtils.rightPad("bat", 5, "yz")  = "batyz"
   * StringUtils.rightPad("bat", 8, "yz")  = "batyzyzy"
   * StringUtils.rightPad("bat", 1, "yz")  = "bat"
   * StringUtils.rightPad("bat", -1, "yz") = "bat"
   * StringUtils.rightPad("bat", 5, null)  = "bat  "
   * StringUtils.rightPad("bat", 5, "")    = "bat  "
   * 
  *
  * @param str  the String to pad out, may be null
  * @param size  the size to pad to
  * @param padStr  the String to pad with, null or empty treated as single space
  * @return right padded String or original String if no padding is necessary,
  *  null if null String input
  */
 public static String rightPad(String str, int size, String padStr) {
     if (str == null) {
         return null;
     }
     if (isEmpty(padStr)) {
         padStr = " ";
     }
     int padLen = padStr.length();
     int strLen = str.length();
     int pads = size - strLen;
     if (pads <= 0) {
         return str; // returns original String when possible
     }
     if (padLen == 1 && pads <= PAD_LIMIT) {
         return rightPad(str, size, padStr.charAt(0));
     }
     if (pads == padLen) {
         return str.concat(padStr);
     } else if (pads < padLen) {
         return str.concat(padStr.substring(0, pads));
     } else {
         char[] padding = new char[pads];
         char[] padChars = padStr.toCharArray();
         for (int i = 0; i < pads; i++) {
             padding[i] = padChars[i % padLen];
         }
         return str.concat(new String(padding));
     }
 }
 /**
  * Returns padding using the specified delimiter repeated
  * to a given length.
  *
*
   * StringUtils.padding(0, "e")  = ""
   * StringUtils.padding(3, "e")  = "eee"
   * StringUtils.padding(-2, "e") = IndexOutOfBoundsException
   * 
  *
  * Note: this method doesn"t not support padding with
  * 
  * as they require a pair of chars to be represented.
  * If you are needing to support full I18N of your applications
  * consider using {@link #repeat(String, int)} instead. 
  * 
  *
  * @param repeat  number of times to repeat delim
  * @param padChar  character to repeat
  * @return String with repeated character
  * @throws IndexOutOfBoundsException if repeat < 0
  * @see #repeat(String, int)
  */
 private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException {
     if (repeat < 0) {
         throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat);
     }
     final char[] buf = new char[repeat];
     for (int i = 0; i < buf.length; i++) {
         buf[i] = padChar;
     }
     return new String(buf);
 }
 // Empty checks
 //-----------------------------------------------------------------------
 /**
  * Checks if a String is empty ("") or null.
  *
*
   * StringUtils.isEmpty(null)      = true
   * StringUtils.isEmpty("")        = true
   * StringUtils.isEmpty(" ")       = false
   * StringUtils.isEmpty("bob")     = false
   * StringUtils.isEmpty("  bob  ") = false
   * 
  *
  * NOTE: This method changed in Lang version 2.0.
  * It no longer trims the String.
  * That functionality is available in isBlank().
  *
  * @param str  the String to check, may be null
  * @return true if the String is empty or null
  */
 public static boolean isEmpty(String str) {
     return str == null || str.length() == 0;
 }

}</source>





String.format(): left pad a string

   <source lang="java">

public class Main {

 public static void main(String[] argv) {
   System.out.println(">" + padLeft("asdf", 10) + "<");
 }
 public static String padLeft(String s, int n) {
   return String.format("%1$#" + n + "s", s);
 }

} //> asdf<</source>





String.format(): right pad a string

   <source lang="java">

public class Main {

 public static void main(String[] argv) {
   System.out.println(">" + padRight("asdf", 10) + "<");
 }
 public static String padRight(String s, int n) {
   return String.format("%1$-" + n + "s", s);
 }

} //>asdf <</source>





Strip Line Breaks

   <source lang="java">

/**

* 
* The ObjectStyle Group Software License, version 1.1
* ObjectStyle Group - http://objectstyle.org/
* 
* Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
* of the software. All rights reserved.
* 
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in
*    the documentation and/or other materials provided with the
*    distribution.
* 
* 3. The end-user documentation included with the redistribution, if any,
*    must include the following acknowlegement:
*    "This product includes software developed by independent contributors
*    and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
*    Alternately, this acknowlegement may appear in the software itself,
*    if and wherever such third-party acknowlegements normally appear.
* 
* 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
*    or promote products derived from this software without prior written
*    permission. For written permission, email
*    "andrus at objectstyle dot org".
* 
* 5. Products derived from this software may not be called "ObjectStyle"
*    or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
*    names without prior written permission.
* 
* THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED.  IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* 
* This software consists of voluntary contributions made by many
* individuals and hosted on ObjectStyle Group web site.  For more
* information on the ObjectStyle Group, please see
* <http://objectstyle.org/>.
*/

import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.lang.reflect.Member; import java.lang.reflect.Modifier; import java.net.URL; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.ruparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /**

* Contains various unorganized static utility methods used across Cayenne.
* 
* @author Andrei Adamchik
*/

public class Util {

 /**
  * Strips "\n", "\r\n", "\r" from the argument string.
  * 
  * @since 1.2
  */
 public static String stripLineBreaks(String string, String replaceWith) {
     int len = string.length();
     StringBuffer buffer = new StringBuffer(len);
     for (int i = 0; i < len; i++) {
         char c = string.charAt(i);
         // skip \n, \r, \r\n
         switch (c) {
             case "\n":
             case "\r": // do lookahead
                 if (i + 1 < len && string.charAt(i + 1) == "\n") {
                     i++;
                 }
                 buffer.append(replaceWith);
                 break;
             default:
                 buffer.append(c);
         }
     }
     return buffer.toString();
 }

}</source>





Transforms words to singular, plural, humanized (human readable), underscore, camel case, or ordinal form

   <source lang="java">

/*

* JBoss DNA (http://www.jboss.org/dna)
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership.  Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
* See the AUTHORS.txt file in the distribution for a full listing of 
* individual contributors. 
*
* JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
* is licensed to you under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* JBoss DNA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/

import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /**

* Transforms words to singular, plural, humanized (human readable), underscore, camel case, or ordinal form. This is inspired by
* the .
* 
* @author Randall Hauch
*/

public class Inflector {

   protected static final Inflector INSTANCE = new Inflector();
   public static final Inflector getInstance() {
       return INSTANCE;
   }
   protected class Rule {
       protected final String expression;
       protected final Pattern expressionPattern;
       protected final String replacement;
       protected Rule( String expression,
                       String replacement ) {
           this.expression = expression;
           this.replacement = replacement != null ? replacement : "";
           this.expressionPattern = Pattern.rupile(this.expression, Pattern.CASE_INSENSITIVE);
       }
       /**
        * Apply the rule against the input string, returning the modified string or null if the rule didn"t apply (and no
        * modifications were made)
        * 
        * @param input the input string
        * @return the modified string if this rule applied, or null if the input was not modified by this rule
        */
       protected String apply( String input ) {
           Matcher matcher = this.expressionPattern.matcher(input);
           if (!matcher.find()) return null;
           return matcher.replaceAll(this.replacement);
       }
       @Override
       public int hashCode() {
           return expression.hashCode();
       }
       @Override
       public boolean equals( Object obj ) {
           if (obj == this) return true;
           if (obj != null && obj.getClass() == this.getClass()) {
               final Rule that = (Rule)obj;
               if (this.expression.equalsIgnoreCase(that.expression)) return true;
           }
           return false;
       }
       @Override
       public String toString() {
           return expression + ", " + replacement;
       }
   }
   private LinkedList<Rule> plurals = new LinkedList<Rule>();
   private LinkedList<Rule> singulars = new LinkedList<Rule>();
   /**
    * The lowercase words that are to be excluded and not processed. This map can be modified by the users via
    * {@link #getUncountables()}.
    */
   private final Set<String> uncountables = new HashSet<String>();
   public Inflector() {
       initialize();
   }
   protected Inflector( Inflector original ) {
       this.plurals.addAll(original.plurals);
       this.singulars.addAll(original.singulars);
       this.uncountables.addAll(original.uncountables);
   }
   @Override
   public Inflector clone() {
       return new Inflector(this);
   }
   // ------------------------------------------------------------------------------------------------
   // Usage functions
   // ------------------------------------------------------------------------------------------------
   /**
    * Returns the plural form of the word in the string.
    * 
    * Examples:
    * 
*
     *   inflector.pluralize("post")               #=> "posts"
     *   inflector.pluralize("octopus")            #=> "octopi"
     *   inflector.pluralize("sheep")              #=> "sheep"
     *   inflector.pluralize("words")              #=> "words"
     *   inflector.pluralize("the blue mailman")   #=> "the blue mailmen"
     *   inflector.pluralize("CamelOctopus")       #=> "CamelOctopi"
     * 
    * 
    * 
    * 
    * Note that if the {@link Object#toString()} is called on the supplied object, so this method works for non-strings, too.
    * 
    * 
    * @param word the word that is to be pluralized.
    * @return the pluralized form of the word, or the word itself if it could not be pluralized
    * @see #singularize(Object)
    */
   public String pluralize( Object word ) {
       if (word == null) return null;
       String wordStr = word.toString().trim();
       if (wordStr.length() == 0) return wordStr;
       if (isUncountable(wordStr)) return wordStr;
       for (Rule rule : this.plurals) {
           String result = rule.apply(wordStr);
           if (result != null) return result;
       }
       return wordStr;
   }
   public String pluralize( Object word,
                            int count ) {
       if (word == null) return null;
       if (count == 1 || count == -1) {
           return word.toString();
       }
       return pluralize(word);
   }
   /**
    * Returns the singular form of the word in the string.
    * 
    * Examples:
    * 
*
     *   inflector.singularize("posts")             #=> "post"
     *   inflector.singularize("octopi")            #=> "octopus"
     *   inflector.singularize("sheep")             #=> "sheep"
     *   inflector.singularize("words")             #=> "word"
     *   inflector.singularize("the blue mailmen")  #=> "the blue mailman"
     *   inflector.singularize("CamelOctopi")       #=> "CamelOctopus"
     * 
    * 
    * 
    * 
    * Note that if the {@link Object#toString()} is called on the supplied object, so this method works for non-strings, too.
    * 
    * 
    * @param word the word that is to be pluralized.
    * @return the pluralized form of the word, or the word itself if it could not be pluralized
    * @see #pluralize(Object)
    */
   public String singularize( Object word ) {
       if (word == null) return null;
       String wordStr = word.toString().trim();
       if (wordStr.length() == 0) return wordStr;
       if (isUncountable(wordStr)) return wordStr;
       for (Rule rule : this.singulars) {
           String result = rule.apply(wordStr);
           if (result != null) return result;
       }
       return wordStr;
   }
   /**
    * Converts strings to lowerCamelCase. This method will also use any extra delimiter characters to identify word boundaries.
    * 
    * Examples:
    * 
*
     *   inflector.lowerCamelCase("active_record")       #=> "activeRecord"
     *   inflector.lowerCamelCase("first_name")          #=> "firstName"
     *   inflector.lowerCamelCase("name")                #=> "name"
     *   inflector.lowerCamelCase("the-first_name","-")  #=> "theFirstName"
     * 
    * 
    * 
    * 
    * @param lowerCaseAndUnderscoredWord the word that is to be converted to camel case
    * @param delimiterChars optional characters that are used to delimit word boundaries
    * @return the lower camel case version of the word
    * @see #underscore(String, char[])
    * @see #camelCase(String, boolean, char[])
    * @see #upperCamelCase(String, char[])
    */
   public String lowerCamelCase( String lowerCaseAndUnderscoredWord,
                                 char... delimiterChars ) {
       return camelCase(lowerCaseAndUnderscoredWord, false, delimiterChars);
   }
   /**
    * Converts strings to UpperCamelCase. This method will also use any extra delimiter characters to identify word boundaries.
    * 
    * Examples:
    * 
*
     *   inflector.upperCamelCase("active_record")       #=> "SctiveRecord"
     *   inflector.upperCamelCase("first_name")          #=> "FirstName"
     *   inflector.upperCamelCase("name")                #=> "Name"
     *   inflector.lowerCamelCase("the-first_name","-")  #=> "TheFirstName"
     * 
    * 
    * 
    * 
    * @param lowerCaseAndUnderscoredWord the word that is to be converted to camel case
    * @param delimiterChars optional characters that are used to delimit word boundaries
    * @return the upper camel case version of the word
    * @see #underscore(String, char[])
    * @see #camelCase(String, boolean, char[])
    * @see #lowerCamelCase(String, char[])
    */
   public String upperCamelCase( String lowerCaseAndUnderscoredWord,
                                 char... delimiterChars ) {
       return camelCase(lowerCaseAndUnderscoredWord, true, delimiterChars);
   }
   /**
    * By default, this method converts strings to UpperCamelCase. If the uppercaseFirstLetter argument to false,
    * then this method produces lowerCamelCase. This method will also use any extra delimiter characters to identify word
    * boundaries.
    * 
    * Examples:
    * 
*
     *   inflector.camelCase("active_record",false)    #=> "activeRecord"
     *   inflector.camelCase("active_record",true)     #=> "ActiveRecord"
     *   inflector.camelCase("first_name",false)       #=> "firstName"
     *   inflector.camelCase("first_name",true)        #=> "FirstName"
     *   inflector.camelCase("name",false)             #=> "name"
     *   inflector.camelCase("name",true)              #=> "Name"
     * 
    * 
    * 
    * 
    * @param lowerCaseAndUnderscoredWord the word that is to be converted to camel case
    * @param uppercaseFirstLetter true if the first character is to be uppercased, or false if the first character is to be
    *        lowercased
    * @param delimiterChars optional characters that are used to delimit word boundaries
    * @return the camel case version of the word
    * @see #underscore(String, char[])
    * @see #upperCamelCase(String, char[])
    * @see #lowerCamelCase(String, char[])
    */
   public String camelCase( String lowerCaseAndUnderscoredWord,
                            boolean uppercaseFirstLetter,
                            char... delimiterChars ) {
       if (lowerCaseAndUnderscoredWord == null) return null;
       lowerCaseAndUnderscoredWord = lowerCaseAndUnderscoredWord.trim();
       if (lowerCaseAndUnderscoredWord.length() == 0) return "";
       if (uppercaseFirstLetter) {
           String result = lowerCaseAndUnderscoredWord;
           // Replace any extra delimiters with underscores (before the underscores are converted in the next step)...
           if (delimiterChars != null) {
               for (char delimiterChar : delimiterChars) {
                   result = result.replace(delimiterChar, "_");
               }
           }
           // Change the case at the beginning at after each underscore ...
           return replaceAllWithUppercase(result, "(^|_)(.)", 2);
       }
       if (lowerCaseAndUnderscoredWord.length() < 2) return lowerCaseAndUnderscoredWord;
       return "" + Character.toLowerCase(lowerCaseAndUnderscoredWord.charAt(0))
              + camelCase(lowerCaseAndUnderscoredWord, true, delimiterChars).substring(1);
   }
   /**
    * Makes an underscored form from the expression in the string (the reverse of the {@link #camelCase(String, boolean, char[])
    * camelCase} method. Also changes any characters that match the supplied delimiters into underscore.
    * 
    * Examples:
    * 
*
     *   inflector.underscore("activeRecord")     #=> "active_record"
     *   inflector.underscore("ActiveRecord")     #=> "active_record"
     *   inflector.underscore("firstName")        #=> "first_name"
     *   inflector.underscore("FirstName")        #=> "first_name"
     *   inflector.underscore("name")             #=> "name"
     *   inflector.underscore("The.firstName")    #=> "the_first_name"
     * 
    * 
    * 
    * 
    * @param camelCaseWord the camel-cased word that is to be converted;
    * @param delimiterChars optional characters that are used to delimit word boundaries (beyond capitalization)
    * @return a lower-cased version of the input, with separate words delimited by the underscore character.
    */
   public String underscore( String camelCaseWord,
                             char... delimiterChars ) {
       if (camelCaseWord == null) return null;
       String result = camelCaseWord.trim();
       if (result.length() == 0) return "";
       result = result.replaceAll("([A-Z]+)([A-Z][a-z])", "$1_$2");
       result = result.replaceAll("([a-z\\d])([A-Z])", "$1_$2");
       result = result.replace("-", "_");
       if (delimiterChars != null) {
           for (char delimiterChar : delimiterChars) {
               result = result.replace(delimiterChar, "_");
           }
       }
       return result.toLowerCase();
   }
   /**
    * Returns a copy of the input with the first character converted to uppercase and the remainder to lowercase.
    * 
    * @param words the word to be capitalized
    * @return the string with the first character capitalized and the remaining characters lowercased
    */
   public String capitalize( String words ) {
       if (words == null) return null;
       String result = words.trim();
       if (result.length() == 0) return "";
       if (result.length() == 1) return result.toUpperCase();
       return "" + Character.toUpperCase(result.charAt(0)) + result.substring(1).toLowerCase();
   }
   /**
    * Capitalizes the first word and turns underscores into spaces and strips trailing "_id" and any supplied removable tokens.
    * Like {@link #titleCase(String, String[])}, this is meant for creating pretty output.
    * 
    * Examples:
    * 
*
     *   inflector.humanize("employee_salary")       #=> "Employee salary"
     *   inflector.humanize("author_id")             #=> "Author"
     * 
    * 
    * 
    * 
    * @param lowerCaseAndUnderscoredWords the input to be humanized
    * @param removableTokens optional array of tokens that are to be removed
    * @return the humanized string
    * @see #titleCase(String, String[])
    */
   public String humanize( String lowerCaseAndUnderscoredWords,
                           String... removableTokens ) {
       if (lowerCaseAndUnderscoredWords == null) return null;
       String result = lowerCaseAndUnderscoredWords.trim();
       if (result.length() == 0) return "";
       // Remove a trailing "_id" token
       result = result.replaceAll("_id$", "");
       // Remove all of the tokens that should be removed
       if (removableTokens != null) {
           for (String removableToken : removableTokens) {
               result = result.replaceAll(removableToken, "");
           }
       }
       result = result.replaceAll("_+", " "); // replace all adjacent underscores with a single space
       return capitalize(result);
   }
   /**
    * Capitalizes all the words and replaces some characters in the string to create a nicer looking title. Underscores are
    * changed to spaces, a trailing "_id" is removed, and any of the supplied tokens are removed. Like
    * {@link #humanize(String, String[])}, this is meant for creating pretty output.
    * 
    * Examples:
    * 
*
     *   inflector.titleCase("man from the boondocks")       #=> "Man From The Boondocks"
     *   inflector.titleCase("x-men: the last stand")        #=> "X Men: The Last Stand"
     * 
    * 
    * 
    * 
    * @param words the input to be turned into title case
    * @param removableTokens optional array of tokens that are to be removed
    * @return the title-case version of the supplied words
    */
   public String titleCase( String words,
                            String... removableTokens ) {
       String result = humanize(words, removableTokens);
       result = replaceAllWithUppercase(result, "\\b([a-z])", 1); // change first char of each word to uppercase
       return result;
   }
   /**
    * Turns a non-negative number into an ordinal string used to denote the position in an ordered sequence, such as 1st, 2nd,
    * 3rd, 4th.
    * 
    * @param number the non-negative number
    * @return the string with the number and ordinal suffix
    */
   public String ordinalize( int number ) {
       int remainder = number % 100;
       String numberStr = Integer.toString(number);
       if (11 <= number && number <= 13) return numberStr + "th";
       remainder = number % 10;
       if (remainder == 1) return numberStr + "st";
       if (remainder == 2) return numberStr + "nd";
       if (remainder == 3) return numberStr + "rd";
       return numberStr + "th";
   }
   // ------------------------------------------------------------------------------------------------
   // Management methods
   // ------------------------------------------------------------------------------------------------
   /**
    * Determine whether the supplied word is considered uncountable by the {@link #pluralize(Object) pluralize} and
    * {@link #singularize(Object) singularize} methods.
    * 
    * @param word the word
    * @return true if the plural and singular forms of the word are the same
    */
   public boolean isUncountable( String word ) {
       if (word == null) return false;
       String trimmedLower = word.trim().toLowerCase();
       return this.uncountables.contains(trimmedLower);
   }
   /**
    * Get the set of words that are not processed by the Inflector. The resulting map is directly modifiable.
    * 
    * @return the set of uncountable words
    */
   public Set<String> getUncountables() {
       return uncountables;
   }
   public void addPluralize( String rule,
                             String replacement ) {
       final Rule pluralizeRule = new Rule(rule, replacement);
       this.plurals.addFirst(pluralizeRule);
   }
   public void addSingularize( String rule,
                               String replacement ) {
       final Rule singularizeRule = new Rule(rule, replacement);
       this.singulars.addFirst(singularizeRule);
   }
   public void addIrregular( String singular,
                             String plural ) {
       //CheckArg.isNotEmpty(singular, "singular rule");
       //CheckArg.isNotEmpty(plural, "plural rule");
       String singularRemainder = singular.length() > 1 ? singular.substring(1) : "";
       String pluralRemainder = plural.length() > 1 ? plural.substring(1) : "";
       addPluralize("(" + singular.charAt(0) + ")" + singularRemainder + "$", "$1" + pluralRemainder);
       addSingularize("(" + plural.charAt(0) + ")" + pluralRemainder + "$", "$1" + singularRemainder);
   }
   public void addUncountable( String... words ) {
       if (words == null || words.length == 0) return;
       for (String word : words) {
           if (word != null) uncountables.add(word.trim().toLowerCase());
       }
   }
   /**
    * Utility method to replace all occurrences given by the specific backreference with its uppercased form, and remove all
    * other backreferences.
    * 
    * The Java {@link Pattern regular expression processing} does not use the preprocessing directives \l,
    * \u, \L, and \U. If so, such directives could be used in the replacement string
    * to uppercase or lowercase the backreferences. For example, \L1 would lowercase the first backreference, and
    * \u3 would uppercase the 3rd backreference.
    * 
    * 
    * @param input
    * @param regex
    * @param groupNumberToUppercase
    * @return the input string with the appropriate characters converted to upper-case
    */
   protected static String replaceAllWithUppercase( String input,
                                                    String regex,
                                                    int groupNumberToUppercase ) {
       Pattern underscoreAndDotPattern = Pattern.rupile(regex);
       Matcher matcher = underscoreAndDotPattern.matcher(input);
       StringBuffer sb = new StringBuffer();
       while (matcher.find()) {
           matcher.appendReplacement(sb, matcher.group(groupNumberToUppercase).toUpperCase());
       }
       matcher.appendTail(sb);
       return sb.toString();
   }
   /**
    * Completely remove all rules within this inflector.
    */
   public void clear() {
       this.uncountables.clear();
       this.plurals.clear();
       this.singulars.clear();
   }
   protected void initialize() {
       Inflector inflect = this;
       inflect.addPluralize("$", "s");
       inflect.addPluralize("s$", "s");
       inflect.addPluralize("(ax|test)is$", "$1es");
       inflect.addPluralize("(octop|vir)us$", "$1i");
       inflect.addPluralize("(octop|vir)i$", "$1i"); // already plural
       inflect.addPluralize("(alias|status)$", "$1es");
       inflect.addPluralize("(bu)s$", "$1ses");
       inflect.addPluralize("(buffal|tomat)o$", "$1oes");
       inflect.addPluralize("([ti])um$", "$1a");
       inflect.addPluralize("([ti])a$", "$1a"); // already plural
       inflect.addPluralize("sis$", "ses");
       inflect.addPluralize("(?:([^f])fe|([lr])f)$", "$1$2ves");
       inflect.addPluralize("(hive)$", "$1s");
       inflect.addPluralize("([^aeiouy]|qu)y$", "$1ies");
       inflect.addPluralize("(x|ch|ss|sh)$", "$1es");
       inflect.addPluralize("(matr|vert|ind)ix|ex$", "$1ices");
       inflect.addPluralize("([m|l])ouse$", "$1ice");
       inflect.addPluralize("([m|l])ice$", "$1ice");
       inflect.addPluralize("^(ox)$", "$1en");
       inflect.addPluralize("(quiz)$", "$1zes");
       // Need to check for the following words that are already pluralized:
       inflect.addPluralize("(people|men|children|sexes|moves|stadiums)$", "$1"); // irregulars
       inflect.addPluralize("(oxen|octopi|viri|aliases|quizzes)$", "$1"); // special rules
       inflect.addSingularize("s$", "");
       inflect.addSingularize("(s|si|u)s$", "$1s"); // "-us" and "-ss" are already singular
       inflect.addSingularize("(n)ews$", "$1ews");
       inflect.addSingularize("([ti])a$", "$1um");
       inflect.addSingularize("((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$", "$1$2sis");
       inflect.addSingularize("(^analy)ses$", "$1sis");
       inflect.addSingularize("(^analy)sis$", "$1sis"); // already singular, but ends in "s"
       inflect.addSingularize("([^f])ves$", "$1fe");
       inflect.addSingularize("(hive)s$", "$1");
       inflect.addSingularize("(tive)s$", "$1");
       inflect.addSingularize("([lr])ves$", "$1f");
       inflect.addSingularize("([^aeiouy]|qu)ies$", "$1y");
       inflect.addSingularize("(s)eries$", "$1eries");
       inflect.addSingularize("(m)ovies$", "$1ovie");
       inflect.addSingularize("(x|ch|ss|sh)es$", "$1");
       inflect.addSingularize("([m|l])ice$", "$1ouse");
       inflect.addSingularize("(bus)es$", "$1");
       inflect.addSingularize("(o)es$", "$1");
       inflect.addSingularize("(shoe)s$", "$1");
       inflect.addSingularize("(cris|ax|test)is$", "$1is"); // already singular, but ends in "s"
       inflect.addSingularize("(cris|ax|test)es$", "$1is");
       inflect.addSingularize("(octop|vir)i$", "$1us");
       inflect.addSingularize("(octop|vir)us$", "$1us"); // already singular, but ends in "s"
       inflect.addSingularize("(alias|status)es$", "$1");
       inflect.addSingularize("(alias|status)$", "$1"); // already singular, but ends in "s"
       inflect.addSingularize("^(ox)en", "$1");
       inflect.addSingularize("(vert|ind)ices$", "$1ex");
       inflect.addSingularize("(matr)ices$", "$1ix");
       inflect.addSingularize("(quiz)zes$", "$1");
       inflect.addIrregular("person", "people");
       inflect.addIrregular("man", "men");
       inflect.addIrregular("child", "children");
       inflect.addIrregular("sex", "sexes");
       inflect.addIrregular("move", "moves");
       inflect.addIrregular("stadium", "stadiums");
       inflect.addUncountable("equipment", "information", "rice", "money", "species", "series", "fish", "sheep");
   }

}</source>





Trim any of the characters

   <source lang="java">

/*

* Static String formatting and query routines.
* Copyright (C) 2001-2005 Stephen Ostermiller
* http://ostermiller.org/contact.pl?regarding=Java+Utilities
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* See COPYING.TXT for details.
*/

import java.util.HashMap; import java.util.regex.Pattern; /**

* Utilities for String formatting, manipulation, and queries.
* More information about this class is available from .
*
* @author Stephen Ostermiller http://ostermiller.org/contact.pl?regarding=Java+Utilities
* @since ostermillerutils 1.00.00
*/

public class StringHelper {

 /**
  * Trim any of the characters contained in the second
  * string from the beginning and end of the first.
  *
  * @param s String to be trimmed.
  * @param c list of characters to trim from s.
  * @return trimmed String.
  * @throws NullPointerException if s is null.
  *
  * @since ostermillerutils 1.00.00
  */
 public static String trim(String s, String c){
   int length = s.length();
   if (c == null){
     return s;
   }
   int cLength = c.length();
   if (c.length() == 0){
     return s;
   }
   int start = 0;
   int end = length;
   boolean found; // trim-able character found.
   int i;
   // Start from the beginning and find the
   // first non-trim-able character.
   found = false;
   for (i=0; !found && i<length; i++){
     char ch = s.charAt(i);
     found = true;
     for (int j=0; found && j<cLength; j++){
       if (c.charAt(j) == ch) found = false;
     }
   }
   // if all characters are trim-able.
   if (!found) return "";
   start = i-1;
   // Start from the end and find the
   // last non-trim-able character.
   found = false;
   for (i=length-1; !found && i>=0; i--){
     char ch = s.charAt(i);
     found = true;
     for (int j=0; found && j<cLength; j++){
       if (c.charAt(j) == ch) found = false;
     }
   }
   end = i+2;
   return s.substring(start, end);
 }

}</source>





Trim off trailing blanks but not leading blanks

   <source lang="java">

/*

Derby - Class org.apache.derby.iapi.util.PropertyUtil
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.  You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

public class Main {

 /**
  * Trim off trailing blanks but not leading blanks
  *
  * @param str
  *
  * @return The input with trailing blanks stipped off
  */
 public static String trimTrailing( String str)
 {
     if( str == null)
         return null;
     int len = str.length();
     for( ; len > 0; len--)
     {
         if( ! Character.isWhitespace( str.charAt( len - 1)))
             break;
     }
     return str.substring( 0, len);
 } // end of trimTrailing

}</source>





Truncate a String to the given length with no warnings or error raised if it is bigger.

   <source lang="java">

/*

Derby - Class org.apache.derby.iapi.util.PropertyUtil
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.  You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

public class Main {

 /**
 Truncate a String to the given length with no warnings
 or error raised if it is bigger.
 @param  value String to be truncated
 @param  length  Maximum length of string
 @return Returns value if value is null or value.length() is less or equal to than length, otherwise a String representing
   value truncated to length.
  • /

public static String truncate(String value, int length) {

 if (value != null && value.length() > length)
   value = value.substring(0, length);
 return value;

}

}</source>





Uncapitalizes a String changing the first letter to title case as per Character.toLowerCase(char). No other letters are changed.

   <source lang="java">

/*

* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
* 
*      http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

public class Main {

 /**
  * Uncapitalizes a String changing the first letter to title case as
  * per {@link Character#toLowerCase(char)}. No other letters are changed.
  *
  * For a word based algorithm, see {@link WordUtils#uncapitalize(String)}.
  * A null input String returns null.
  *
*
   * StringUtils.uncapitalize(null)  = null
   * StringUtils.uncapitalize("")    = ""
   * StringUtils.uncapitalize("Cat") = "cat"
   * StringUtils.uncapitalize("CAT") = "cAT"
   * 
  *
  * @param str  the String to uncapitalize, may be null
  * @return the uncapitalized String, null if null String input
  * @see WordUtils#uncapitalize(String)
  * @see #capitalize(String)
  * @since 2.0
  */
 public static String uncapitalize(String str) {
     int strLen;
     if (str == null || (strLen = str.length()) == 0) {
         return str;
     }
     return new StringBuffer(strLen)
         .append(Character.toLowerCase(str.charAt(0)))
         .append(str.substring(1))
         .toString();
 }

}</source>