Java/Data Type/String Pad
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 Left pad a String with a specified character.
- 2 Left pad a String with a specified String.
- 3 Left pad a String with spaces (" ").
- 4 Padded String
- 5 Padding and triming strings
- 6 Pad string
- 7 Return a string padded with the given string for the given count.
- 8 Returns the quoted version of the string using the quotechar argument.
- 9 Right pad a String with a specified character.
- 10 Right pad a String with a specified String.
- 11 Right pad a String with spaces (" ").
- 12 Set string length, padding with character if the shorter, or truncating if longer
Left pad a String with a specified character.
/*
* 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 {
/**
* <p>The maximum size to which the padding constant(s) can expand.</p>
*/
private static final int PAD_LIMIT = 8192;
/**
* <p>Left pad a String with a specified character.</p>
*
* <p>Pad to a size of <code>size</code>.</p>
*
* <pre>
* 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"
* </pre>
*
* @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,
* <code>null</code> 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);
}
/**
* <p>Left pad a String with a specified String.</p>
*
* <p>Pad to a size of <code>size</code>.</p>
*
* <pre>
* 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"
* </pre>
*
* @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,
* <code>null</code> 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);
}
}
/**
* <p>Returns padding using the specified delimiter repeated
* to a given length.</p>
*
* <pre>
* StringUtils.padding(0, "e") = ""
* StringUtils.padding(3, "e") = "eee"
* StringUtils.padding(-2, "e") = IndexOutOfBoundsException
* </pre>
*
* <p>Note: this method doesn"t not support padding with
*
* as they require a pair of <code>char</code>s to be represented.
* If you are needing to support full I18N of your applications
* consider using {@link #repeat(String, int)} instead.
* </p>
*
* @param repeat number of times to repeat delim
* @param padChar character to repeat
* @return String with repeated character
* @throws IndexOutOfBoundsException if <code>repeat < 0</code>
* @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
//-----------------------------------------------------------------------
/**
* <p>Checks if a String is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the String.
* That functionality is available in isBlank().</p>
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is empty or null
*/
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
}
Left pad a String with a specified String.
/*
* 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 {
/**
* <p>The maximum size to which the padding constant(s) can expand.</p>
*/
private static final int PAD_LIMIT = 8192;
/**
* <p>Left pad a String with a specified character.</p>
*
* <p>Pad to a size of <code>size</code>.</p>
*
* <pre>
* 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"
* </pre>
*
* @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,
* <code>null</code> 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);
}
/**
* <p>Left pad a String with a specified String.</p>
*
* <p>Pad to a size of <code>size</code>.</p>
*
* <pre>
* 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"
* </pre>
*
* @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,
* <code>null</code> 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);
}
}
/**
* <p>Returns padding using the specified delimiter repeated
* to a given length.</p>
*
* <pre>
* StringUtils.padding(0, "e") = ""
* StringUtils.padding(3, "e") = "eee"
* StringUtils.padding(-2, "e") = IndexOutOfBoundsException
* </pre>
*
* <p>Note: this method doesn"t not support padding with
*
* as they require a pair of <code>char</code>s to be represented.
* If you are needing to support full I18N of your applications
* consider using {@link #repeat(String, int)} instead.
* </p>
*
* @param repeat number of times to repeat delim
* @param padChar character to repeat
* @return String with repeated character
* @throws IndexOutOfBoundsException if <code>repeat < 0</code>
* @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
//-----------------------------------------------------------------------
/**
* <p>Checks if a String is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the String.
* That functionality is available in isBlank().</p>
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is empty or null
*/
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
}
Left pad a String with spaces (" ").
/*
* 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 {
/**
* <p>The maximum size to which the padding constant(s) can expand.</p>
*/
private static final int PAD_LIMIT = 8192;
/**
* <p>Left pad a String with spaces (" ").</p>
*
* <p>The String is padded to the size of <code>size<code>.</p>
*
* <pre>
* 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"
* </pre>
*
* @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</code> if null String input
*/
public static String leftPad(String str, int size) {
return leftPad(str, size, " ");
}
/**
* <p>Left pad a String with a specified character.</p>
*
* <p>Pad to a size of <code>size</code>.</p>
*
* <pre>
* 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"
* </pre>
*
* @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,
* <code>null</code> 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);
}
/**
* <p>Left pad a String with a specified String.</p>
*
* <p>Pad to a size of <code>size</code>.</p>
*
* <pre>
* 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"
* </pre>
*
* @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,
* <code>null</code> 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);
}
}
/**
* <p>Returns padding using the specified delimiter repeated
* to a given length.</p>
*
* <pre>
* StringUtils.padding(0, "e") = ""
* StringUtils.padding(3, "e") = "eee"
* StringUtils.padding(-2, "e") = IndexOutOfBoundsException
* </pre>
*
* <p>Note: this method doesn"t not support padding with
*
* as they require a pair of <code>char</code>s to be represented.
* If you are needing to support full I18N of your applications
* consider using {@link #repeat(String, int)} instead.
* </p>
*
* @param repeat number of times to repeat delim
* @param padChar character to repeat
* @return String with repeated character
* @throws IndexOutOfBoundsException if <code>repeat < 0</code>
* @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
//-----------------------------------------------------------------------
/**
* <p>Checks if a String is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the String.
* That functionality is available in isBlank().</p>
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is empty or null
*/
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
}
Padded String
/**********************************************************************
Copyright (c) 2003 Andy Jefferson and others. All rights reserved.
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.
Contributors:
2003 Erik Bengtson - moved replaceAll from Column class to here
2004 Andy Jefferson - moved intArrayToString, booleanArrayToString from SM
2007 Xuan Baldauf - toJVMIDString hex fix
...
**********************************************************************/
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.jar.JarFile;
/**
* Utilities for String manipulation.
*
* @version $Revision: 1.23 $
**/
public class StringUtils
{
/** Utility to return a left-aligned version of a string padded to the
* number of characters specified.
* @param input The input string
* @param length The length desired
* @return The updated string
**/
public static String leftAlignedPaddedString(String input,int length)
{
if (length <= 0)
{
return null;
}
StringBuffer output=new StringBuffer();
char space=" ";
if (input != null)
{
if (input.length() < length)
{
output.append(input);
for (int i=input.length();i<length;i++)
{
output.append(space);
}
}
else
{
output.append(input.substring(0,length));
}
}
else
{
for (int i=0;i<length;i++)
{
output.append(space);
}
}
return output.toString();
}
/** Utility to return a right-aligned version of a string padded to the
* number of characters specified.
* @param input The input string
* @param length The length desired
* @return The updated string
**/
public static String rightAlignedPaddedString(String input,int length)
{
if (length <= 0)
{
return null;
}
StringBuffer output=new StringBuffer();
char space=" ";
if (input != null)
{
if (input.length() < length)
{
for (int i=input.length();i<length;i++)
{
output.append(space);
}
output.append(input);
}
else
{
output.append(input.substring(0,length));
}
}
else
{
for (int i=0;i<length;i++)
{
output.append(space);
}
}
return output.toString();
}
}
Padding and triming strings
/**
* The utillib library.
* More information is available at http://www.jinchess.ru/.
* Copyright (C) 2002-2003 Alexander Maryanovsky.
* All rights reserved.
*
* The utillib library 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 of the
* License, or (at your option) any later version.
*
* The utillib library 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 utillib library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.util.StringTokenizer;
/**
* A utility class which provides many useful text manipulation methods.
*/
public class TextUtilities{
/**
* Pads the beginning of the given String with the given character until it"s
* <code>length</code> characters long. If the given String"s size is already
* <code>length</code> or larger, the given string is returned as is.
*/
public static String padStart(String s, char c, int length){
if (s.length()>=length)
return s;
StringBuffer buf = new StringBuffer(s);
for (int i=s.length();i<length;i++)
buf.insert(0,c);
return buf.toString();
}
/**
* Pads the end of the given String with the given character until it"s
* <code>length</code> characters long. If the given String"s size is already
* <code>length</code> or larger, the given string is returned as is.
*/
public static String padEnd(String s, char c, int length){
if (s.length()>=length)
return s;
StringBuffer buf = new StringBuffer(s);
for (int i=s.length();i<length;i++)
buf.append(c);
return buf.toString();
}
/**
* Pads the given String on both sides equally (if possible) with the given
* character until it"s <code>length</code> characters long. If the given
* String"s size is already <code>length</code> or larger, the given
* string is returned as is.
*/
public static String padSides(String s, char c, int length){
if (s.length()>=length)
return s;
StringBuffer buf = new StringBuffer(s);
for (int i=s.length();i<length-1;i+=2){
buf.insert(0,c);
buf.append(c);
}
if (buf.length()<length)
buf.insert(0,c);
return buf.toString();
}
/**
* Trims the specified string on the right only.
*/
public static String trimRight(String s){
StringBuffer buf = new StringBuffer(s);
int length = buf.length();
while (Character.isWhitespace(buf.charAt(length - 1)))
buf.setLength(--length);
return buf.toString();
}
/**
* Trims the specified string on the left only.
*/
public static String trimLeft(String s){
int i = 0;
while (Character.isWhitespace(s.charAt(i)))
i++;
return s.substring(i);
}
/**
* <P>Returns a substring of the given StringBuffer"s string which consists of
* the characters from the beginning of it until the first occurrence of the
* given delimiter string or if the delimiter doesn"t occur, until the end
* of the string. The StringBuffer is modified so it no longer contains those
* characters or the delimiter.
* <P>Examples:
* <UL>
* <LI>nextToken(new StringBuffer("abcdefgh"), "de") returns "abc" and
* the StringBuffer is modified to represent the string "fgh".
* <LI>nextToken(new StringBuffer("abcdefgh"), "a") returns an empty string
* and the StringBuffer is modified to represent the string "bcdefgh".
* <LI>nextToken(new StringBuffer("abcdefgh"), "k") returns "abcdefgh" and
* the StringBuffer is modified to represent an empty string.
* </UL>
*/
public static String nextToken(StringBuffer buf, String delimiter){
String bufStr = buf.toString();
int delimIndex = bufStr.indexOf(delimiter);
if (delimIndex==-1){
buf.setLength(0);
return bufStr;
}
String str = bufStr.substring(0,delimIndex);
buf.reverse();
buf.setLength(buf.length()-delimIndex-delimiter.length());
buf.reverse();
return str;
}
/**
* Returns an array of the tokens produced by the specified string with the
* specified delimiter characters.
*/
public static String [] getTokens(String text, String delimiters){
StringTokenizer tokenizer = new StringTokenizer(text, delimiters);
String [] tokens = new String[tokenizer.countTokens()];
for (int i = 0; i < tokens.length; i++)
tokens[i] = tokenizer.nextToken();
return tokens;
}
/**
* Parses the specified list of integers delimited by the specified
* delimiters.
*/
public static int [] parseIntList(String text, String delimiters){
StringTokenizer tokenizer = new StringTokenizer(text, delimiters);
int [] tokens = new int[tokenizer.countTokens()];
for (int i = 0; i < tokens.length; i++)
tokens[i] = Integer.parseInt(tokenizer.nextToken());
return tokens;
}
/**
* Translates the specified resource name into the context of the specified
* class. Basically, this method returns the name of the resource you need to
* use when loading via a classloader, if via the specified class you would
* load it simply with <code>Class.getResource(resourceName)</code>.
*/
public static String translateResource(Class c, String resourceName){
String path = c.getName();
int dotIndex = path.lastIndexOf(".");
if (dotIndex != -1){
path = path.substring(0, dotIndex);
path = path.replace(".", "/") + "/" + resourceName;
}
else
return resourceName;
return path;
}
/**
* Breaks the specified text into lines no longer than the specified length,
* without breaking words. The breaking is done by inserting newlines at
* appropriate locations. Note that if there are words longer than
* <code>maxLength</code>, they will not be broken.
*/
public static String breakIntoLines(String text, int maxLength){
StringBuffer buf = new StringBuffer(text);
text = text + " "; // Fake an extra space at the end to simplify the algorithm
int lastNewline = -1; // The index of the last newline
int lastSpace = -1; // The index of the last space
int curSpace; // The index of the current space
while ((curSpace = text.indexOf(" ", lastSpace + 1)) != -1){
if ((curSpace - lastNewline - 1 > maxLength) && (lastSpace > lastNewline)){
// lastSpace == lastNewline means the current word is longer than maxLength
buf.setCharAt(lastSpace, "\n");
lastNewline = lastSpace;
}
lastSpace = curSpace;
}
return buf.toString();
}
}
Pad string
/*
* 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 {
/**
* Pad the beginning of the given String with spaces until
* the String is of the given length.
* <p>
* If a String is longer than the desired length,
* it will not be truncated, however no padding
* will be added.
*
* @param s String to be padded.
* @param length desired length of result.
* @return padded String.
* @throws NullPointerException if s is null.
*
* @since ostermillerutils 1.00.00
*/
public static String prepad(String s, int length){
return prepad(s, length, " ");
}
/**
* Pre-pend the given character to the String until
* the result is the desired length.
* <p>
* If a String is longer than the desired length,
* it will not be truncated, however no padding
* will be added.
*
* @param s String to be padded.
* @param length desired length of result.
* @param c padding character.
* @return padded String.
* @throws NullPointerException if s is null.
*
* @since ostermillerutils 1.00.00
*/
public static String prepad(String s, int length, char c){
int needed = length - s.length();
if (needed <= 0){
return s;
}
char padding[] = new char[needed];
java.util.Arrays.fill(padding, c);
StringBuffer sb = new StringBuffer(length);
sb.append(padding);
sb.append(s);
return sb.toString();
}
/**
* Pad the end of the given String with spaces until
* the String is of the given length.
* <p>
* If a String is longer than the desired length,
* it will not be truncated, however no padding
* will be added.
*
* @param s String to be padded.
* @param length desired length of result.
* @return padded String.
* @throws NullPointerException if s is null.
*
* @since ostermillerutils 1.00.00
*/
public static String postpad(String s, int length){
return postpad(s, length, " ");
}
/**
* Append the given character to the String until
* the result is the desired length.
* <p>
* If a String is longer than the desired length,
* it will not be truncated, however no padding
* will be added.
*
* @param s String to be padded.
* @param length desired length of result.
* @param c padding character.
* @return padded String.
* @throws NullPointerException if s is null.
*
* @since ostermillerutils 1.00.00
*/
public static String postpad(String s, int length, char c){
int needed = length - s.length();
if (needed <= 0){
return s;
}
char padding[] = new char[needed];
java.util.Arrays.fill(padding, c);
StringBuffer sb = new StringBuffer(length);
sb.append(s);
sb.append(padding);
return sb.toString();
}
/**
* Pad the beginning and end of the given String with spaces until
* the String is of the given length. The result is that the original
* String is centered in the middle of the new string.
* <p>
* If the number of characters to pad is even, then the padding
* will be split evenly between the beginning and end, otherwise,
* the extra character will be added to the end.
* <p>
* If a String is longer than the desired length,
* it will not be truncated, however no padding
* will be added.
*
* @param s String to be padded.
* @param length desired length of result.
* @return padded String.
* @throws NullPointerException if s is null.
*
* @since ostermillerutils 1.00.00
*/
public static String midpad(String s, int length){
return midpad(s, length, " ");
}
/**
* Pad the beginning and end of the given String with the given character
* until the result is the desired length. The result is that the original
* String is centered in the middle of the new string.
* <p>
* If the number of characters to pad is even, then the padding
* will be split evenly between the beginning and end, otherwise,
* the extra character will be added to the end.
* <p>
* If a String is longer than the desired length,
* it will not be truncated, however no padding
* will be added.
*
* @param s String to be padded.
* @param length desired length of result.
* @param c padding character.
* @return padded String.
* @throws NullPointerException if s is null.
*
* @since ostermillerutils 1.00.00
*/
public static String midpad(String s, int length, char c){
int needed = length - s.length();
if (needed <= 0){
return s;
}
int beginning = needed / 2;
int end = beginning + needed % 2;
char prepadding[] = new char[beginning];
java.util.Arrays.fill(prepadding, c);
char postpadding[] = new char[end];
java.util.Arrays.fill(postpadding, c);
StringBuffer sb = new StringBuffer(length);
sb.append(prepadding);
sb.append(s);
sb.append(postpadding);
return sb.toString();
}
}
Return a string padded with the given string for the given count.
/*
* 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{
/////////////////////////////////////////////////////////////////////////
// Padding Methods //
/////////////////////////////////////////////////////////////////////////
/**
* Return a string padded with the given string for the given count.
*
* @param buff String buffer used for padding (buffer is not reset).
* @param string Pad element.
* @param count Pad count.
* @return Padded string.
*/
public static String pad(final StringBuffer buff, final String string,
final int count)
{
for (int i = 0; i < count; i++)
{
buff.append(string);
}
return buff.toString();
}
/**
* Return a string padded with the given string for the given count.
*
* @param string Pad element.
* @param count Pad count.
* @return Padded string.
*/
public static String pad(final String string, final int count)
{
return pad(new StringBuffer(), string, count);
}
/**
* Return a string padded with the given string value of an object
* for the given count.
*
* @param obj Object to convert to a string.
* @param count Pad count.
* @return Padded string.
*/
public static String pad(final Object obj, final int count)
{
return pad(new StringBuffer(), String.valueOf(obj), count);
}
}
Returns the quoted version of the string using the quotechar argument.
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
/* Copyright (c) 1995-2000, The Hypersonic SQL Group.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 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.
*
* Neither the name of the Hypersonic SQL Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 HYPERSONIC SQL GROUP,
* OR 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
* on behalf of the Hypersonic SQL Group.
*
*
* For work added by the HSQL Development Group:
*
* Copyright (c) 2001-2009, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 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.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS 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 HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR 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.
*/
/**
* Collection of static methods for converting strings between different formats
* and to and from byte arrays.
* <p>
*
* Includes some methods based on Hypersonic code as indicated.
*
* @author Thomas Mueller (Hypersonic SQL Group)
* @author Fred Toussi (fredt@users dot sourceforge.net)
* @version 1.9.0
* @since 1.7.2
*/
public class Main {
/**
* Returns the quoted version of the string using the quotechar argument.
* doublequote argument indicates whether each instance of quotechar inside
* the string is doubled.<p>
*
* null string argument returns null. If the caller needs the literal
* "NULL" it should created it itself<p>
*
* @param s Java string
* @param quoteChar character used for quoting
* @param extraQuote true if quoteChar itself should be repeated
* @return String
*/
public static String toQuotedString(String s, char quoteChar,
boolean extraQuote) {
if (s == null) {
return null;
}
int count = extraQuote ? count(s, quoteChar)
: 0;
int len = s.length();
char[] b = new char[2 + count + len];
int i = 0;
int j = 0;
b[j++] = quoteChar;
for (; i < len; i++) {
char c = s.charAt(i);
b[j++] = c;
if (extraQuote && c == quoteChar) {
b[j++] = c;
}
}
b[j] = quoteChar;
return new String(b);
}
/**
* Counts Character c in String s
*
* @param s Java string
* @param c character to count
* @return int count
*/
static int count(final String s, final char c) {
int pos = 0;
int count = 0;
if (s != null) {
while ((pos = s.indexOf(c, pos)) > -1) {
count++;
pos++;
}
}
return count;
}
}
Right pad a String with a specified character.
/*
* 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 {
/**
* <p>The maximum size to which the padding constant(s) can expand.</p>
*/
private static final int PAD_LIMIT = 8192;
/**
* <p>Right pad a String with a specified character.</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* 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"
* </pre>
*
* @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,
* <code>null</code> 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));
}
/**
* <p>Right pad a String with a specified String.</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* 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 "
* </pre>
*
* @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,
* <code>null</code> 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));
}
}
/**
* <p>Returns padding using the specified delimiter repeated
* to a given length.</p>
*
* <pre>
* StringUtils.padding(0, "e") = ""
* StringUtils.padding(3, "e") = "eee"
* StringUtils.padding(-2, "e") = IndexOutOfBoundsException
* </pre>
*
* <p>Note: this method doesn"t not support padding with
*
* as they require a pair of <code>char</code>s to be represented.
* If you are needing to support full I18N of your applications
* consider using {@link #repeat(String, int)} instead.
* </p>
*
* @param repeat number of times to repeat delim
* @param padChar character to repeat
* @return String with repeated character
* @throws IndexOutOfBoundsException if <code>repeat < 0</code>
* @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
//-----------------------------------------------------------------------
/**
* <p>Checks if a String is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the String.
* That functionality is available in isBlank().</p>
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is empty or null
*/
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
}
Right pad a String with a specified String.
/*
* 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 {
/**
* <p>The maximum size to which the padding constant(s) can expand.</p>
*/
private static final int PAD_LIMIT = 8192;
/**
* <p>Right pad a String with a specified character.</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* 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"
* </pre>
*
* @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,
* <code>null</code> 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));
}
/**
* <p>Right pad a String with a specified String.</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* 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 "
* </pre>
*
* @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,
* <code>null</code> 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));
}
}
/**
* <p>Returns padding using the specified delimiter repeated
* to a given length.</p>
*
* <pre>
* StringUtils.padding(0, "e") = ""
* StringUtils.padding(3, "e") = "eee"
* StringUtils.padding(-2, "e") = IndexOutOfBoundsException
* </pre>
*
* <p>Note: this method doesn"t not support padding with
*
* as they require a pair of <code>char</code>s to be represented.
* If you are needing to support full I18N of your applications
* consider using {@link #repeat(String, int)} instead.
* </p>
*
* @param repeat number of times to repeat delim
* @param padChar character to repeat
* @return String with repeated character
* @throws IndexOutOfBoundsException if <code>repeat < 0</code>
* @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
//-----------------------------------------------------------------------
/**
* <p>Checks if a String is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the String.
* That functionality is available in isBlank().</p>
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is empty or null
*/
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
}
Right pad a String with spaces (" ").
/*
* 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 {
/**
* <p>The maximum size to which the padding constant(s) can expand.</p>
*/
private static final int PAD_LIMIT = 8192;
/**
* <p>Right pad a String with spaces (" ").</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* 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"
* </pre>
*
* @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,
* <code>null</code> if null String input
*/
public static String rightPad(String str, int size) {
return rightPad(str, size, " ");
}
/**
* <p>Right pad a String with a specified character.</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* 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"
* </pre>
*
* @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,
* <code>null</code> 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));
}
/**
* <p>Right pad a String with a specified String.</p>
*
* <p>The String is padded to the size of <code>size</code>.</p>
*
* <pre>
* 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 "
* </pre>
*
* @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,
* <code>null</code> 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));
}
}
/**
* <p>Returns padding using the specified delimiter repeated
* to a given length.</p>
*
* <pre>
* StringUtils.padding(0, "e") = ""
* StringUtils.padding(3, "e") = "eee"
* StringUtils.padding(-2, "e") = IndexOutOfBoundsException
* </pre>
*
* <p>Note: this method doesn"t not support padding with
*
* as they require a pair of <code>char</code>s to be represented.
* If you are needing to support full I18N of your applications
* consider using {@link #repeat(String, int)} instead.
* </p>
*
* @param repeat number of times to repeat delim
* @param padChar character to repeat
* @return String with repeated character
* @throws IndexOutOfBoundsException if <code>repeat < 0</code>
* @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
//-----------------------------------------------------------------------
/**
* <p>Checks if a String is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the String.
* That functionality is available in isBlank().</p>
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is empty or null
*/
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
}
Set string length, padding with character if the shorter, or truncating if longer
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
* 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.
*/
/**
* Utilities for string processing and manipulation.
*/
public class StringUtil {
/**
* Set the length of the string, padding with the supplied character if the
* supplied string is shorter than desired, or truncating the string if it is
* longer than desired. Unlike {@link #justifyLeft(String, int, char)}, this
* method does not remove leading and trailing whitespace.
*
* @param original
* the string for which the length is to be set; may not be null
* @param length
* the desired length; must be positive
* @param padChar
* the character to use for padding, if the supplied string is not
* long enough
* @return the string of the desired length
* @see #justifyLeft(String, int, char)
*/
public static String setLength(String original, int length, char padChar) {
return justifyLeft(original, length, padChar, false);
}
protected static String justifyLeft(String str, final int width, char padWithChar,
boolean trimWhitespace) {
// Trim the leading and trailing whitespace ...
str = str != null ? (trimWhitespace ? str.trim() : str) : "";
int addChars = width - str.length();
if (addChars < 0) {
// truncate
return str.subSequence(0, width).toString();
}
// Write the content ...
final StringBuilder sb = new StringBuilder();
sb.append(str);
// Append the whitespace ...
while (addChars > 0) {
sb.append(padWithChar);
--addChars;
}
return sb.toString();
}
}