Java/Data Type/String format
Содержание
- 1 Abbreviates a String using ellipses.
- 2 Abbreviates a String using ellipses in both sides.
- 3 Abbreviate string
- 4 Adds spaces in suitable locations of the input string
- 5 Adds zeros to the beginning of a value so that the total length matches the given precision, otherwise trims the right digits.
- 6 Blank string: empty or white space
- 7 break Lines
- 8 Capital and uncapital strings
- 9 Capitalizes a String changing the first letter to title case as Character.toTitleCase(char). No other letters are changed.
- 10 Capitalizes the first character of the given string
- 11 Capitalize the first character of the given string
- 12 Capitalize the first letter but leave the rest as they are.
- 13 Capitlize each word in a string (journal titles, etc)
- 14 Centers a String in a larger String of size size. Uses a supplied character as the value to pad the String with.
- 15 Centers a String in a larger String of size size. Uses a supplied String as the value to pad the String with.
- 16 Centers a String in a larger String of size size using the space character (" ").
- 17 Center the contents of the string.
- 18 Constructs a method name from element"s bean name for a given prefix
- 19 convert String array To Comma Delimited
- 20 Demonstrate some usage patterns and format-code examples of the Formatter
- 21 Escapes all necessary characters in the String so that it can be used in an XML doc
- 22 Escapes all necessary characters in the String so that it can be used in SQL
- 23 Fast lower case conversion
- 24 Fmt - format text (like Berkeley UNIX fmt)
- 25 Format a percentage for presentation to the user
- 26 Format a String (JDK1.5)
- 27 Format Calendar with String.format()
- 28 Format strings into table
- 29 Left justify the contents of the string, ensuring that the supplied string begins at the first character and that the resulting string is of the desired length.
- 30 Limit the string to a certain number of characters, adding "..." if it was truncated
- 31 Makes the first letter caps and the rest lowercase.
- 32 Pass value array to String.format()
- 33 Quote a string so that it can be used as an identifier or a string literal in SQL statements.
- 34 Remove the hyphens from the begining of str and return the new String.
- 35 Replace, remove, format strings
- 36 Right justify string, ensuring that the string ends at the last character
- 37 String.format(): left pad a string
- 38 String.format(): right pad a string
- 39 Swaps the case of a String changing upper and title case to lower case, and lower case to upper case.
- 40 Transforms words to singular, plural, humanized (human readable), underscore, camel case, or ordinal form
- 41 Truncate the supplied string to be no more than the specified length.
- 42 Uncapitalizes a String changing the first letter to title case as per Character.toLowerCase(char). No other letters are changed.
- 43 Uncapitalize String
- 44 Utilities for String formatting, manipulation, and queries
- 45 Utility inserts a space before every caps in a string
- 46 Word Wrap
Abbreviates a String using ellipses.
/*
* 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
//-----------------------------------------------------------------------
/**
* <p>Abbreviates a String using ellipses. This will turn
* "Now is the time for all good men" into "Now is the time for..."</p>
*
* <p>Specifically:
* <ul>
* <li>If <code>str</code> is less than <code>maxWidth</code> characters
* long, return it.</li>
* <li>Else abbreviate it to <code>(substring(str, 0, max-3) + "...")</code>.</li>
* <li>If <code>maxWidth</code> is less than <code>4</code>, throw an
* <code>IllegalArgumentException</code>.</li>
* <li>In no case will it return a String of length greater than
* <code>maxWidth</code>.</li>
* </ul>
* </p>
*
* <pre>
* 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
* </pre>
*
* @param str the String to check, may be null
* @param maxWidth maximum length of result String, must be at least 4
* @return abbreviated String, <code>null</code> 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);
}
/**
* <p>Abbreviates a String using ellipses. This will turn
* "Now is the time for all good men" into "...is the time for..."</p>
*
* <p>Works like <code>abbreviate(String, int)</code>, 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.
*
* <p>In no case will it return a String of length greater than
* <code>maxWidth</code>.</p>
*
* <pre>
* 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
* </pre>
*
* @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, <code>null</code> 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));
}
}
Abbreviates a String using ellipses in both sides.
/*
* 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
//-----------------------------------------------------------------------
/**
* <p>Abbreviates a String using ellipses. This will turn
* "Now is the time for all good men" into "Now is the time for..."</p>
*
* <p>Specifically:
* <ul>
* <li>If <code>str</code> is less than <code>maxWidth</code> characters
* long, return it.</li>
* <li>Else abbreviate it to <code>(substring(str, 0, max-3) + "...")</code>.</li>
* <li>If <code>maxWidth</code> is less than <code>4</code>, throw an
* <code>IllegalArgumentException</code>.</li>
* <li>In no case will it return a String of length greater than
* <code>maxWidth</code>.</li>
* </ul>
* </p>
*
* <pre>
* 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
* </pre>
*
* @param str the String to check, may be null
* @param maxWidth maximum length of result String, must be at least 4
* @return abbreviated String, <code>null</code> 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);
}
/**
* <p>Abbreviates a String using ellipses. This will turn
* "Now is the time for all good men" into "...is the time for..."</p>
*
* <p>Works like <code>abbreviate(String, int)</code>, 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.
*
* <p>In no case will it return a String of length greater than
* <code>maxWidth</code>.</p>
*
* <pre>
* 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
* </pre>
*
* @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, <code>null</code> 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));
}
}
Abbreviate string
/**
* $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.
*/
/**
* Utility class to peform common String manipulation algorithms.
*/
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:
* <pre>
* user1@jivesoftware.ru/home
* </pre>
* and a maximum length of 20 characters, the abbreviate method will return:
* <pre>
* user1@jivesoftware.c...
* </pre>
* @param str the String to abbreviate.
* @param maxWidth the maximum size of the string, minus the ellipsis.
* @return the abbreviated String, or <tt>null</tt> if the string was <tt>null</tt>.
*/
public static String abbreviate(String str, int maxWidth) {
if (null == str) {
return null;
}
if (str.length() <= maxWidth) {
return str;
}
return str.substring(0, maxWidth) + "...";
}
}
Adds spaces in suitable locations of the input string
/*
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.Properties;
import java.util.Random;
public class StringUtils
{
private static final int EOI = 0;
private static final int LOWER = 1;
private static final int UPPER = 2;
private static final int DIGIT = 3;
private static final int OTHER = 4;
private static int getCharKind(int c)
{
if (c==-1)
{
return EOI;
}
char ch = (char) c;
if (Character.isLowerCase(ch))
return LOWER;
else if (Character.isUpperCase(ch))
return UPPER;
else if (Character.isDigit(ch))
return DIGIT;
else
return OTHER;
}
/**
* Adds spaces in suitable locations of the input string. This is
* used to transform a WikiName into a more readable format.
*
* @param s String to be beautified.
* @return A beautified string.
*/
public static String beautifyString( String s )
{
return beautifyString( s, " " );
}
/**
* Adds spaces in suitable locations of the input string. This is
* used to transform a WikiName into a more readable format.
*
* @param s String to be beautified.
* @param space Use this string for the space character.
* @return A beautified string.
* @since 2.1.127
*/
public static String beautifyString( String s, String space )
{
StringBuffer result = new StringBuffer();
if( s == null || s.length() == 0 ) return "";
int cur = s.charAt(0);
int curKind = getCharKind(cur);
int prevKind = LOWER;
int nextKind = -1;
int next = -1;
int nextPos = 1;
while( curKind != EOI )
{
next = (nextPos < s.length()) ? s.charAt(nextPos++) : -1;
nextKind = getCharKind( next );
if( (prevKind == UPPER) && (curKind == UPPER) && (nextKind == LOWER) )
{
result.append(space);
result.append((char) cur);
}
else
{
result.append((char) cur);
if( ( (curKind == UPPER) && (nextKind == DIGIT) )
|| ( (curKind == LOWER) && ((nextKind == DIGIT) || (nextKind == UPPER)) )
|| ( (curKind == DIGIT) && ((nextKind == UPPER) || (nextKind == LOWER)) ))
{
result.append(space);
}
}
prevKind = curKind;
cur = next;
curKind = nextKind;
}
return result.toString();
}
}
Adds zeros to the beginning of a value so that the total length matches the given precision, otherwise trims the right digits.
/* 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.
*/
/** Provides a collection of convenience methods for processing and
* creating objects with <code>String</code> value components.
*
* @author Campbell Boucher-Burnett (boucherb@users dot sourceforge.net)
* @author Fred Toussi (fredt@users dot sourceforge.net)
* @author Nitin Chauhan
* @version 1.9.0
* @since 1.7.0
*/
public class Main {
/**
* If necessary, adds zeros to the beginning of a value so that the total
* length matches the given precision, otherwise trims the right digits.
* Then if maxSize is smaller than precision, trims the right digits to
* maxSize. Negative values are treated as positive
*/
public static String toZeroPaddedString(long value, int precision,
int maxSize) {
StringBuffer sb = new StringBuffer();
if (value < 0) {
value = -value;
}
String s = Long.toString(value);
if (s.length() > precision) {
s = s.substring(precision);
}
for (int i = s.length(); i < precision; i++) {
sb.append("0");
}
sb.append(s);
if (maxSize < precision) {
sb.setLength(maxSize);
}
return sb.toString();
}
}
Blank string: empty or white space
/**
* Copyright (C) 2007 Google Inc.
*
* This 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.1 of the License, or (at your option) any later version.
* This 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 this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
/**
* String utilities.
*
* @author maxr@google.ru (Max Ross)
*/
public class StringUtil {
/**
* Helper function for null, empty, and whitespace string testing.
*
* @return true if s == null or s.equals("") or s contains only whitespace
* characters.
*/
public static boolean isEmptyOrWhitespace(String s) {
s = makeSafe(s);
for (int i = 0, n = s.length(); i < n; i++) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
/**
* @return true if s == null or s.equals("")
*/
public static boolean isEmpty(String s) {
return makeSafe(s).length() == 0;
}
/**
* Helper function for making null strings safe for comparisons, etc.
*
* @return (s == null) ? "" : s;
*/
public static String makeSafe(String s) {
return (s == null) ? "" : s;
}
/**
* @return the string provided with its first character capitalized
*/
public static String capitalize(String s) {
if (s.length() == 0) {
return s;
}
char first = s.charAt(0);
char capitalized = Character.toUpperCase(first);
return (first == capitalized)
? s
: capitalized + s.substring(1);
}
}
break Lines
public class Utils {
public static final String breakLines(String s, int width) {
s = " " + s;
int n = 0;
boolean moreLines = true;
StringBuffer buffer = new StringBuffer();
if ((s == null) || (s.length() <= width)) return s;
while (moreLines) {
for (int i = width; i > 0; i--) {
if (s.charAt(n + i) == " ") {
buffer.append(s.substring(n, n + i) + "\n ");
n = n + i + 1;
break;
}
}
if ((n + width) >= s.length()) {
buffer.append(s.substring(n));
moreLines = false;
}
}
return buffer.toString();
}
}
Capital and uncapital strings
/* ------------------------------------------------------------------------
* $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());
}
}
Capitalizes a String changing the first letter to title case as Character.toTitleCase(char). No other letters are changed.
/*
* 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>Capitalizes a String changing the first letter to title case as
* per {@link Character#toTitleCase(char)}. No other letters are changed.</p>
*
* <p>For a word based algorithm, see {@link WordUtils#capitalize(String)}.
* A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.capitalize(null) = null
* StringUtils.capitalize("") = ""
* StringUtils.capitalize("cat") = "Cat"
* StringUtils.capitalize("cAt") = "CAt"
* </pre>
*
* @param str the String to capitalize, may be null
* @return the capitalized String, <code>null</code> if null String input
* @see WordUtils#capitalize(String)
* @see #uncapitalize(String)
* @since 2.0
*/
public static String capitalize(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
return new StringBuffer(strLen)
.append(Character.toTitleCase(str.charAt(0)))
.append(str.substring(1))
.toString();
}
}
Capitalizes the first character of the given string
/*
* The contents of this file are subject to the Sapient Public License
* Version 1.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://carbon.sf.net/License.html.
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The Original Code is The Carbon Component Framework.
*
* The Initial Developer of the Original Code is Sapient Corporation
*
* Copyright (C) 2003 Sapient Corporation. All Rights Reserved.
*/
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
/**
* <p>Utilities for strings.</p>
*
*
* Copyright 2002 Sapient
* @since carbon 1.0
* @author Greg Hinkle, May 2002
* @version $Revision: 1.5 $($Author: dvoet $ / $Date: 2003/05/05 21:21:24 $)
*/
public class StringUtil {
/**
* Capitalizes the first character of the given string.
* @param s the String to capitalize
* @return the capitalized result
*/
public static String capitalize(String s) {
if (s.length() == 0) return s;
char c = Character.toUpperCase(s.charAt(0));
return c + s.substring(1, s.length());
}
}
Capitalize the first character of the given string
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);
}
}
Capitalize the first letter but leave the rest as they are.
public class Main {
/**
* <p>
* Capitalize the first letter but leave the rest as they are.
* </p>
*
* @param data capitalize this
* @return String
*/
static public String capitalizeFirstLetter ( String data )
{
String firstLetter = data.substring(0,1).toUpperCase();
String restLetters = data.substring(1);
return firstLetter + restLetters;
}
}
Capitlize each word in a string (journal titles, etc)
/**********************************************************************************
*
* Copyright (c) 2003, 2004 The Regents of the University of Michigan, Trustees of Indiana University,
* Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation
*
* Licensed under the Educational Community License Version 1.0 (the "License");
* By obtaining, using and/or copying this Original Work, you agree that you have read,
* understand, and will comply with the terms and conditions of the Educational Community License.
* You may obtain a copy of the License at:
*
* http://cvs.sakaiproject.org/licenses/license_1_0.html
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**********************************************************************************/
public class Utils {
/**
* Capitlize each word in a string (journal titles, etc)
*
* @param text
* Text to inspect
* @return Capitalized text
*/
public static String capitalize(String text) {
StringBuilder resultText;
char previousC;
resultText = new StringBuilder();
previousC = ".";
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (Character.isLetter(c) && !Character.isLetter(previousC)) {
resultText.append(Character.toUpperCase(c));
} else {
resultText.append(c);
}
previousC = c;
}
return resultText.toString();
}
}
Centers a String in a larger String of size size. Uses a supplied character as the value to pad the String with.
/*
* 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>Centers a String in a larger String of size <code>size</code>.
* Uses a supplied character as the value to pad the String with.</p>
*
* <p>If the size is less than the String length, the String is returned.
* A <code>null</code> String returns <code>null</code>.
* A negative size is treated as zero.</p>
*
* <pre>
* 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"
* </pre>
*
* @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, <code>null</code> 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;
}
/**
* <p>Centers a String in a larger String of size <code>size</code>.
* Uses a supplied String as the value to pad the String with.</p>
*
* <p>If the size is less than the String length, the String is returned.
* A <code>null</code> String returns <code>null</code>.
* A negative size is treated as zero.</p>
*
* <pre>
* 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 "
* </pre>
*
* @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, <code>null</code> if null String input
* @throws IllegalArgumentException if padStr is <code>null</code> 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;
}
/**
* <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>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;
}
}
Centers a String in a larger String of size size. Uses a supplied String as the value to pad the String with.
/*
* 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>Centers a String in a larger String of size <code>size</code>.
* Uses a supplied String as the value to pad the String with.</p>
*
* <p>If the size is less than the String length, the String is returned.
* A <code>null</code> String returns <code>null</code>.
* A negative size is treated as zero.</p>
*
* <pre>
* 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 "
* </pre>
*
* @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, <code>null</code> if null String input
* @throws IllegalArgumentException if padStr is <code>null</code> 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;
}
/**
* <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>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;
}
}
Centers a String in a larger String of size size using the space 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;
// Centering
//-----------------------------------------------------------------------
/**
* <p>Centers a String in a larger String of size <code>size</code>
* using the space character (" ").<p>
*
* <p>If the size is less than the String length, the String is returned.
* A <code>null</code> String returns <code>null</code>.
* A negative size is treated as zero.</p>
*
* <p>Equivalent to <code>center(str, size, " ")</code>.</p>
*
* <pre>
* 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 "
* </pre>
*
* @param str the String to center, may be null
* @param size the int size of new String, negative treated as zero
* @return centered String, <code>null</code> if null String input
*/
public static String center(String str, int size) {
return center(str, size, " ");
}
/**
* <p>Centers a String in a larger String of size <code>size</code>.
* Uses a supplied character as the value to pad the String with.</p>
*
* <p>If the size is less than the String length, the String is returned.
* A <code>null</code> String returns <code>null</code>.
* A negative size is treated as zero.</p>
*
* <pre>
* 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"
* </pre>
*
* @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, <code>null</code> 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;
}
/**
* <p>Centers a String in a larger String of size <code>size</code>.
* Uses a supplied String as the value to pad the String with.</p>
*
* <p>If the size is less than the String length, the String is returned.
* A <code>null</code> String returns <code>null</code>.
* A negative size is treated as zero.</p>
*
* <pre>
* 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 "
* </pre>
*
* @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, <code>null</code> if null String input
* @throws IllegalArgumentException if padStr is <code>null</code> 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;
}
/**
* <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>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;
}
}
Center the contents of the string.
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 {
/**
* Center the contents of the string. If the supplied string is longer than the desired width, it is truncated to the
* specified length. If the supplied string is shorter than the desired width, padding characters are added to the beginning
* and end of the string such that the length is that specified; one additional padding character is prepended if required.
* All leading and trailing whitespace is removed before centering.
*
* @param str the string to be left justified; if null, an empty string is used
* @param width the desired width of the string; must be positive
* @param padWithChar the character to use for padding, if needed
* @return the left justified string
* @see #setLength(String, int, char)
*/
public static String justifyCenter( String str,
final int width,
char padWithChar ) {
// Trim the leading and trailing whitespace ...
str = str != null ? str.trim() : "";
int addChars = width - str.length();
if (addChars < 0) {
// truncate
return str.subSequence(0, width).toString();
}
// Write the content ...
int prependNumber = addChars / 2;
int appendNumber = prependNumber;
if ((prependNumber + appendNumber) != addChars) {
++prependNumber;
}
final StringBuilder sb = new StringBuilder();
// Prepend the pad character(s) ...
while (prependNumber > 0) {
sb.append(padWithChar);
--prependNumber;
}
// Add the actual content
sb.append(str);
// Append the pad character(s) ...
while (appendNumber > 0) {
sb.append(padWithChar);
--appendNumber;
}
return sb.toString();
}
}
Constructs a method name from element"s bean name for a given prefix
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don"t indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
/**
*
* @author Rajeshwar Patil
* @version %I%, %G%
*/
public class Utils {
/**
* Constructs a method name from element"s bean
* name for a given prefix.(schema2beans convention)
*
* @param elementName the given element name
* @param prefix the given prefix
* @return a method name formed from the given name and the prefix
*/
public String methodNameFromBeanName(String elementName,
String prefix){
if((null == elementName) || (null == prefix) ||
(prefix.length() <= 0 )){
return elementName;
}
String methodName = upperCaseFirstLetter(elementName);
return methodName = prefix + methodName;
}
/**
* Converts the first letter of the given string to Uppercase.
*
* @param string the input string
* @return the string with the Uppercase first letter
*/
public String upperCaseFirstLetter(String string)
{
if(string == null || string.length() <= 0){
return string;
}
return string.substring(0, 1).toUpperCase() + string.substring(1);
}
}
convert String array To Comma Delimited
public abstract class Main {
public static String convertToCommaDelimited(String[] list) {
StringBuffer ret = new StringBuffer("");
for (int i = 0; list != null && i < list.length; i++) {
ret.append(list[i]);
if (i < list.length - 1) {
ret.append(",");
}
}
return ret.toString();
}
}
Demonstrate some usage patterns and format-code examples of the Formatter
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.util.Calendar;
import java.util.Date;
/**
* Demonstrate some usage patterns and format-code examples of the Formatter
* class (new in J2SE 1.5).
*/
public class FormatterDates {
public static void main(String[] args) {
// Format number as dates e.g., 2004-06-28
System.out.printf("%1$4d-%2$02d-%3$2d%n", 2004, 6, 28);
// Format fields directly from a Date object: multiple fields from "1$"
// (hard-coded formatting for Date not advisable; see I18N chapter)
Date today = Calendar.getInstance().getTime();
System.out.printf("Today is %1$tB %1$td, %1$tY%n", today); // e.g., July
// 4, 2004
}
}
Escapes all necessary characters in the String so that it can be used in an XML doc
/**
* $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.
}
/**
* Escapes all necessary characters in the String so that it can be used
* in an XML doc.
*
* @param string the string to escape.
* @return the string with appropriate characters escaped.
*/
public static String escapeForXML(String string) {
if (string == null) {
return null;
}
char ch;
int i = 0;
int last = 0;
char[] input = string.toCharArray();
int len = input.length;
StringBuilder out = new StringBuilder((int)(len * 1.3));
for (; i < len; i++) {
ch = input[i];
if (ch > ">") {
}
else if (ch == "<") {
if (i > last) {
out.append(input, last, i - last);
}
last = i + 1;
out.append(LT_ENCODE);
}
else if (ch == "&") {
if (i > last) {
out.append(input, last, i - last);
}
last = i + 1;
out.append(AMP_ENCODE);
}
else if (ch == """) {
if (i > last) {
out.append(input, last, i - last);
}
last = i + 1;
out.append(QUOTE_ENCODE);
}
}
if (last == 0) {
return string;
}
if (i > last) {
out.append(input, last, i - last);
}
return out.toString();
}
}
Escapes all necessary characters in the String so that it can be used in SQL
/**
* $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.
}
/**
* Escapes all necessary characters in the String so that it can be used in SQL
*
* @param string the string to escape.
* @return the string with appropriate characters escaped.
*/
public static String escapeForSQL(String string) {
if (string == null) {
return null;
}
else if (string.length() == 0) {
return string;
}
char ch;
char[] input = string.toCharArray();
int i = 0;
int last = 0;
int len = input.length;
StringBuilder out = null;
for (; i < len; i++) {
ch = input[i];
if (ch == "\"") {
if (out == null) {
out = new StringBuilder(len + 2);
}
if (i > last) {
out.append(input, last, i - last);
}
last = i + 1;
out.append("\"").append("\"");
}
}
if (out == null) {
return string;
}
else if (i > last) {
out.append(input, last, i - last);
}
return out.toString();
}
}
Fast lower case conversion
//
// Copyright 2004-2005 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// 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.
//
//
/** Fast String Utilities.
*
* These string utilities provide both conveniance methods and
* performance improvements over most standard library versions. The
* main aim of the optimizations is to avoid object creation unless
* absolutely required.
*
* @author Greg Wilkins (gregw)
*/
class StringUtil
{
public static final String CRLF="\015\012";
public static final String __LINE_SEPARATOR=
System.getProperty("line.separator","\n");
public static String __ISO_8859_1;
static
{
String iso=System.getProperty("ISO_8859_1");
if (iso!=null)
__ISO_8859_1=iso;
else
{
try{
new String(new byte[]{(byte)20},"ISO-8859-1");
__ISO_8859_1="ISO-8859-1";
}
catch(java.io.UnsupportedEncodingException e)
{
__ISO_8859_1="ISO8859_1";
}
}
}
public final static String __UTF8="UTF-8";
private static char[] lowercases = {
"\000","\001","\002","\003","\004","\005","\006","\007",
"\010","\011","\012","\013","\014","\015","\016","\017",
"\020","\021","\022","\023","\024","\025","\026","\027",
"\030","\031","\032","\033","\034","\035","\036","\037",
"\040","\041","\042","\043","\044","\045","\046","\047",
"\050","\051","\052","\053","\054","\055","\056","\057",
"\060","\061","\062","\063","\064","\065","\066","\067",
"\070","\071","\072","\073","\074","\075","\076","\077",
"\100","\141","\142","\143","\144","\145","\146","\147",
"\150","\151","\152","\153","\154","\155","\156","\157",
"\160","\161","\162","\163","\164","\165","\166","\167",
"\170","\171","\172","\133","\134","\135","\136","\137",
"\140","\141","\142","\143","\144","\145","\146","\147",
"\150","\151","\152","\153","\154","\155","\156","\157",
"\160","\161","\162","\163","\164","\165","\166","\167",
"\170","\171","\172","\173","\174","\175","\176","\177" };
/* ------------------------------------------------------------ */
/**
* fast lower case conversion. Only works on ascii (not unicode)
* @param s the string to convert
* @return a lower case version of s
*/
public static String asciiToLowerCase(String s)
{
char[] c = null;
int i=s.length();
// look for first conversion
while (i-->0)
{
char c1=s.charAt(i);
if (c1<=127)
{
char c2=lowercases[c1];
if (c1!=c2)
{
c=s.toCharArray();
c[i]=c2;
break;
}
}
}
while (i-->0)
{
if(c[i]<=127)
c[i] = lowercases[c[i]];
}
return c==null?s:new String(c);
}
}
Fmt - format text (like Berkeley UNIX fmt)
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
* Fmt - format text (like Berkeley UNIX fmt).
*/
public class Fmt {
/** The maximum column width */
public static final int COLWIDTH = 72;
/** The file that we read and format */
BufferedReader in;
/** If files present, format each, else format the standard input. */
public static void main(String[] av) throws IOException {
if (av.length == 0)
new Fmt(System.in).format();
else
for (int i = 0; i < av.length; i++)
new Fmt(av[i]).format();
}
/** Construct a Formatter given a filename */
public Fmt(String fname) throws IOException {
in = new BufferedReader(new FileReader(fname));
}
/** Construct a Formatter given an open Stream */
public Fmt(InputStream file) throws IOException {
in = new BufferedReader(new InputStreamReader(file));
}
/** Format the File contained in a constructed Fmt object */
public void format() throws IOException {
String w, f;
int col = 0;
while ((w = in.readLine()) != null) {
if (w.length() == 0) { // null line
System.out.print("\n"); // end current line
if (col > 0) {
System.out.print("\n"); // output blank line
col = 0;
}
continue;
}
// otherwise it"s text, so format it.
StringTokenizer st = new StringTokenizer(w);
while (st.hasMoreTokens()) {
f = st.nextToken();
if (col + f.length() > COLWIDTH) {
System.out.print("\n");
col = 0;
}
System.out.print(f + " ");
col += f.length() + 1;
}
}
if (col > 0)
System.out.print("\n");
in.close();
}
}
Format a percentage for presentation to the user
/**
* 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.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Collection;
/**
* General string utils
*/
public class StringUtils {
final public static char COMMA = ",";
final public static String COMMA_STR = ",";
final public static char ESCAPE_CHAR = "\\";
private static DecimalFormat oneDecimal = new DecimalFormat("0.0");
/**
* Format a percentage for presentation to the user.
* @param done the percentage to format (0.0 to 1.0)
* @param digits the number of digits past the decimal point
* @return a string representation of the percentage
*/
public static String formatPercent(double done, int digits) {
DecimalFormat percentFormat = new DecimalFormat("0.00%");
double scale = Math.pow(10.0, digits+2);
double rounded = Math.floor(done * scale);
percentFormat.setDecimalSeparatorAlwaysShown(false);
percentFormat.setMinimumFractionDigits(digits);
percentFormat.setMaximumFractionDigits(digits);
return percentFormat.format(rounded / scale);
}
}
Format a String (JDK1.5)
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
Format Calendar with String.format()
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 )
Format strings into table
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 |
*/
Left justify the contents of the string, ensuring that the supplied string begins at the first character and that the resulting string is of the desired length.
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 {
/**
* Left justify the contents of the string, ensuring that the supplied string begins at the first character and that the
* resulting string is of the desired length. If the supplied string is longer than the desired width, it is truncated to the
* specified length. If the supplied string is shorter than the desired width, the padding character is added to the end of
* the string one or more times such that the length is that specified. All leading and trailing whitespace is removed.
*
* @param str the string to be left justified; if null, an empty string is used
* @param width the desired width of the string; must be positive
* @param padWithChar the character to use for padding, if needed
* @return the left justified string
* @see #setLength(String, int, char)
*/
public static String justifyLeft( String str,
final int width,
char padWithChar ) {
return justifyLeft(str, width, padWithChar, true);
}
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();
}
}
Limit the string to a certain number of characters, adding "..." if it was truncated
import java.util.Collection;
import java.util.Iterator;
/**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/util/branches/sakai_2-5-4/util-util/util/src/java/org/sakaiproject/util/StringUtil.java $
* $Id: StringUtil.java 34934 2007-09-10 22:52:23Z lance@indiana.edu $
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.
*
**********************************************************************************/
/**
* <p>
* StringUtil collects together some string utility classes.
* </p>
*/
public class StringUtil
{
/**
* Limit the string to a certain number of characters, adding "..." if it was truncated
*
* @param value
* The string to limit.
* @param length
* the length to limit to (as an int).
* @return The limited string.
*/
public static String limit(String value, int length)
{
StringBuilder buf = new StringBuilder(value);
if (buf.length() > length)
{
buf.setLength(length);
buf.append("...");
}
return buf.toString();
}
}
Makes the first letter caps and the rest lowercase.
public class Main {
/**
* <p>
* Makes the first letter caps and the rest lowercase.
* </p>
*
* <p>
* For example <code>fooBar</code> becomes <code>Foobar</code>.
* </p>
*
* @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;
}
}
Pass value array to String.format()
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));
}
}
Quote a string so that it can be used as an identifier or a string literal in SQL statements.
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, "\"");
}
}
Remove the hyphens from the begining of str and return the new 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.
*/
/**
* 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) $
*/
class Util
{
/**
* Remove the hyphens from the begining of <code>str</code> and
* return the new String.
*
* @param str The string from which the hyphens should be removed.
*
* @return the new String.
*/
static String stripLeadingHyphens(String str)
{
if (str == null)
{
return null;
}
if (str.startsWith("--"))
{
return str.substring(2, str.length());
}
else if (str.startsWith("-"))
{
return str.substring(1, str.length());
}
return str;
}
}
Replace, remove, format strings
// Copyright (c) 2003-2009, Jodd Team (jodd.org). All Rights Reserved.
import java.io.UnsupportedEncodingException;
/**
* Various String utilities.
*/
public class StringUtil {
// ---------------------------------------------------------------- replace
/**
* Replaces all occurrences of a certain pattern in a string with a
* replacement string. This is the fastest replace function known to author.
*
* @param s string to be inspected
* @param sub string pattern to be replaced
* @param with string that should go where the pattern was
*/
public static String replace(String s, String sub, String with) {
int c = 0;
int i = s.indexOf(sub, c);
if (i == -1) {
return s;
}
int sLen = s.length();
StringBuilder buf = new StringBuilder(sLen + with.length());
do {
buf.append(s.substring(c,i));
buf.append(with);
c = i + sub.length();
} while ((i = s.indexOf(sub, c)) != -1);
if (c < sLen) {
buf.append(s.substring(c, sLen));
}
return buf.toString();
}
/**
* Replaces all occurrences of a character in a string.
*
* @param s input string
* @param sub character to replace
* @param with character to replace with
*/
public static String replaceChar(String s, char sub, char with) {
char[] str = s.toCharArray();
for (int i = 0; i < str.length; i++) {
if (str[i] == sub) {
str[i] = with;
}
}
return new String(str);
}
/**
* Replaces all occurrences of a characters in a string.
*
* @param s input string
* @param sub characters to replace
* @param with characters to replace with
*/
public static String replaceChars(String s, char[] sub, char[] with) {
char[] str = s.toCharArray();
for (int i = 0; i < str.length; i++) {
char c = str[i];
for (int j = 0; j < sub.length; j++) {
if (c == sub[j]) {
str[i] = with[j];
break;
}
}
}
return new String(str);
}
/**
* Replaces the very first occurrence of a substring with supplied string.
*
* @param s source string
* @param sub substring to replace
* @param with substring to replace with
*/
public static String replaceFirst(String s, String sub, String with) {
int i = s.indexOf(sub);
if (i == -1) {
return s;
}
return s.substring(0, i) + with + s.substring(i + sub.length());
}
/**
* Replaces the very first occurrence of a character in a string.
*
* @param s string
* @param sub char to replace
* @param with char to replace with
*/
public static String replaceFirst(String s, char sub, char with) {
char[] str = s.toCharArray();
for (int i = 0; i < str.length; i++) {
if (str[i] == sub) {
str[i] = with;
break;
}
}
return new String(str);
}
/**
* Replaces the very last occurrence of a substring with supplied string.
*
* @param s source string
* @param sub substring to replace
* @param with substring to replace with
*/
public static String replaceLast(String s, String sub, String with) {
int i = s.lastIndexOf(sub);
if (i == -1) {
return s;
}
return s.substring(0, i) + with + s.substring(i + sub.length());
}
/**
* Replaces the very last occurrence of a character in a string.
*
* @param s string
* @param sub char to replace
* @param with char to replace with
*/
public static String replaceLast(String s, char sub, char with) {
char[] str = s.toCharArray();
for (int i = str.length - 1; i >= 0; i--) {
if (str[i] == sub) {
str[i] = with;
break;
}
}
return new String(str);
}
// ---------------------------------------------------------------- remove
/**
* Removes all substring occurrences from the string.
*
* @param s source string
* @param sub substring to remove
*/
public static String remove(String s, String sub) {
int c = 0;
int sublen = sub.length();
if (sublen == 0) {
return s;
}
int i = s.indexOf(sub, c);
if (i == -1) {
return s;
}
StringBuilder buf = new StringBuilder(s.length());
do {
buf.append(s.substring(c, i));
c = i + sublen;
} while ((i = s.indexOf(sub, c)) != -1);
if (c < s.length()) {
buf.append(s.substring(c, s.length()));
}
return buf.toString();
}
/**
* Removes all characters contained in provided string.
*
* @param src source string
* @param chars string containing characters to remove
*/
public static String removeChars(String src, String chars) {
int i = src.length();
StringBuilder stringbuffer = new StringBuilder(i);
for (int j = 0; j < i; j++) {
char c = src.charAt(j);
if (chars.indexOf(c) == -1) {
stringbuffer.append(c);
}
}
return stringbuffer.toString();
}
/**
* Removes set of characters from string.
*
* @param src string
* @param chars character to remove
*/
public static String removeChars(String src, char[] chars) {
int i = src.length();
StringBuilder stringbuffer = new StringBuilder(i);
mainloop:
for (int j = 0; j < i; j++) {
char c = src.charAt(j);
for (char aChar : chars) {
if (c == aChar) {
continue mainloop;
}
}
stringbuffer.append(c);
}
return stringbuffer.toString();
}
/**
* Removes a single character from string.
*
* @param src source string
* @param chars character to remove
*/
public static String remove(String src, char chars) {
int i = src.length();
StringBuilder stringbuffer = new StringBuilder(i);
for (int j = 0; j < i; j++) {
char c = src.charAt(j);
if (c == chars) {
continue;
}
stringbuffer.append(c);
}
return stringbuffer.toString();
}
// ---------------------------------------------------------------- miscellaneous
/**
* Determines if a string is empty (<code>null</code> or zero-length).
*/
public static boolean isEmpty(String string) {
return ((string == null) || (string.length() == 0));
}
/**
* Determines if a string is blank (<code>null</code> or {@link #containsOnlyWhitespaces(String)}).
*/
public static boolean isBlank(String string) {
return ((string == null) || containsOnlyWhitespaces(string));
}
/**
* Returns <code>true</code> if string contains only spaces.
*/
public static boolean containsOnlyWhitespaces(String string) {
int size = string.length();
for (int i= 0; i < size; i++) {
char c = string.charAt(i);
if (CharUtil.isWhitespace(c) == false) {
return false;
}
}
return true;
}
/**
* Determines if a string is not empty.
*/
public static boolean isNotEmpty(String string) {
return string != null && string.length() > 0;
}
/**
* Converts safely an object to a string. If object is <code>null</code> it will be
* not converted.
*/
public static String toString(Object obj) {
if (obj == null) {
return null;
}
return obj.toString();
}
// ---------------------------------------------------------------- captialize
/**
* Capitalizes a string, changing the first letter to
* upper case. No other letters are changed.
*
* @param str string to capitalize, may be null
* @see #uncapitalize(String)
*/
public static String capitalize(String str) {
return changeFirstCharacterCase(true, str);
}
/**
* Uncapitalizes a <code>String</code>, changing the first letter to
* lower case. No other letters are changed.
*
* @param str the String to uncapitalize, may be null
* @return the uncapitalized String, <code>null</code> if null
* @see #capitalize(String)
*/
public static String uncapitalize(String str) {
return changeFirstCharacterCase(false, str);
}
/**
* Internal method for changing the first character case. It is significantly
* faster using StringBuffers then just simply Strings.
*/
private static String changeFirstCharacterCase(boolean capitalize, String str) {
int strLen = str.length();
if (strLen == 0) {
return str;
}
StringBuilder buf = new StringBuilder(strLen);
if (capitalize) {
buf.append(Character.toUpperCase(str.charAt(0)));
} else {
buf.append(Character.toLowerCase(str.charAt(0)));
}
buf.append(str.substring(1));
return buf.toString();
}
// ---------------------------------------------------------------- truncate
/**
* Sets the maximum length of the string. Longer strings will be simply truncated.
*/
public static String truncate(String string, int length) {
if (string.length() > length) {
string = string.substring(0, length);
}
return string;
}
// ---------------------------------------------------------------- split
/**
* Splits a string in several parts (tokens) that are separated by delimiter.
* Delimiter is <b>always</b> surrounded by two strings! If there is no
* content between two delimiters, empty string will be returned for that
* token. Therefore, the length of the returned array will always be:
* #delimiters + 1.
* <p>
* Method is much, much faster then regexp <code>String.split()</code>,
* and a bit faster then <code>StringTokenizer</code>.
*
* @param src string to split
* @param delimeter split delimiter
*
* @return array of split strings
*/
public static String[] split(String src, String delimeter) {
int maxparts = (src.length() / delimeter.length()) + 2; // one more for the last
int[] positions = new int[maxparts];
int dellen = delimeter.length();
int i, j = 0;
int count = 0;
positions[0] = - dellen;
while ((i = src.indexOf(delimeter, j)) != -1) {
count++;
positions[count] = i;
j = i + dellen;
}
count++;
positions[count] = src.length();
String[] result = new String[count];
for (i = 0; i < count; i++) {
result[i] = src.substring(positions[i] + dellen, positions[i + 1]);
}
return result;
}
// ---------------------------------------------------------------- indexof and ignore cases
/**
* Finds first occurrence of a substring in the given source but within limited range [start, end).
* It is fastest possible code, but still original <code>String.indexOf(String, int)</code>
* is much faster (since it uses char[] value directly) and should be used when no range is needed.
*
* @param src source string for examination
* @param sub substring to find
* @param startIndex starting index
* @param endIndex ending index
* @return index of founded substring or -1 if substring not found
*/
public static int indexOf(String src, String sub, int startIndex, int endIndex) {
if (startIndex < 0) {
startIndex = 0;
}
int srclen = src.length();
if (endIndex > srclen) {
endIndex = srclen;
}
int sublen = sub.length();
if (sublen == 0) {
return startIndex > srclen ? srclen : startIndex;
}
int total = endIndex - sublen + 1;
char c = sub.charAt(0);
mainloop:
for (int i = startIndex; i < total; i++) {
if (src.charAt(i) != c) {
continue;
}
int j = 1;
int k = i + 1;
while (j < sublen) {
if (sub.charAt(j) != src.charAt(k)) {
continue mainloop;
}
j++; k++;
}
return i;
}
return -1;
}
/**
* Finds the first occurrence of a character in the given source but within limited range (start, end].
*/
public static int indexOf(String src, char c, int startIndex, int endIndex) {
if (startIndex < 0) {
startIndex = 0;
}
int srclen = src.length();
if (endIndex > srclen) {
endIndex = srclen;
}
for (int i = startIndex; i < endIndex; i++) {
if (src.charAt(i) == c) {
return i;
}
}
return -1;
}
/**
* Finds the first occurrence of a character in the given source but within limited range (start, end].
*/
public static int indexOfIgnoreCase(String src, char c, int startIndex, int endIndex) {
if (startIndex < 0) {
startIndex = 0;
}
int srclen = src.length();
if (endIndex > srclen) {
endIndex = srclen;
}
c = Character.toLowerCase(c);
for (int i = startIndex; i < endIndex; i++) {
if (Character.toLowerCase(src.charAt(i)) == c) {
return i;
}
}
return -1;
}
/**
* Finds first index of a substring in the given source string with ignored case.
*
* @param src source string for examination
* @param subS substring to find
*
* @return index of founded substring or -1 if substring is not found
* @see #indexOfIgnoreCase(String, String, int)
*/
public static int indexOfIgnoreCase(String src, String subS) {
return indexOfIgnoreCase(src, subS, 0, src.length());
}
/**
* Finds first index of a substring in the given source string with ignored
* case. This seems to be the fastest way doing this, with common string
* length and content (of course, with no use of Boyer-Mayer type of
* algorithms). Other implementations are slower: getting char array first,
* lower casing the source string, using String.regionMatch etc.
*
* @param src source string for examination
* @param subS substring to find
* @param startIndex starting index from where search begins
*
* @return index of founded substring or -1 if substring is not found
*/
public static int indexOfIgnoreCase(String src, String subS, int startIndex) {
return indexOfIgnoreCase(src, subS, startIndex, src.length());
}
/**
* Finds first index of a substring in the given source string and range with
* ignored case.
*
* @param src source string for examination
* @param sub substring to find
* @param startIndex starting index from where search begins
* @param endIndex endint index
* @return index of founded substring or -1 if substring is not found
* @see #indexOfIgnoreCase(String, String, int)
*/
public static int indexOfIgnoreCase(String src, String sub, int startIndex, int endIndex) {
if (startIndex < 0) {
startIndex = 0;
}
int srclen = src.length();
if (endIndex > srclen) {
endIndex = srclen;
}
int sublen = sub.length();
if (sublen == 0) {
return startIndex > srclen ? srclen : startIndex;
}
sub = sub.toLowerCase();
int total = endIndex - sublen + 1;
char c = sub.charAt(0);
mainloop:
for (int i = startIndex; i < total; i++) {
if (Character.toLowerCase(src.charAt(i)) != c) {
continue;
}
int j = 1;
int k = i + 1;
while (j < sublen) {
char source = Character.toLowerCase(src.charAt(k));
if (sub.charAt(j) != source) {
continue mainloop;
}
j++; k++;
}
return i;
}
return -1;
}
/**
* Finds last index of a substring in the given source string with ignored
* case.
*
* @param s source string
* @param subS substring to find
*
* @return last index of founded substring or -1 if substring is not found
* @see #indexOfIgnoreCase(String, String, int)
* @see #lastIndexOfIgnoreCase(String, String, int)
*/
public static int lastIndexOfIgnoreCase(String s, String subS) {
return lastIndexOfIgnoreCase(s, subS, s.length(), 0);
}
/**
* Finds last index of a substring in the given source string with ignored
* case.
*
* @param src source string for examination
* @param subS substring to find
* @param startIndex starting index from where search begins
*
* @return last index of founded substring or -1 if substring is not found
* @see #indexOfIgnoreCase(String, String, int)
*/
public static int lastIndexOfIgnoreCase(String src, String subS, int startIndex) {
return lastIndexOfIgnoreCase(src, subS, startIndex, 0);
}
/**
* Finds last index of a substring in the given source string with ignored
* case in specified range.
*
* @param src source to examine
* @param sub substring to find
* @param startIndex starting index
* @param endIndex end index
* @return last index of founded substring or -1 if substring is not found
*/
public static int lastIndexOfIgnoreCase(String src, String sub, int startIndex, int endIndex) {
int sublen = sub.length();
int srclen = src.length();
if (sublen == 0) {
return startIndex > srclen ? srclen : (startIndex < -1 ? -1 : startIndex);
}
sub = sub.toLowerCase();
int total = srclen - sublen;
if (total < 0) {
return -1;
}
if (startIndex >= total) {
startIndex = total;
}
if (endIndex < 0) {
endIndex = 0;
}
char c = sub.charAt(0);
mainloop:
for (int i = startIndex; i >= endIndex; i--) {
if (Character.toLowerCase(src.charAt(i)) != c) {
continue;
}
int j = 1;
int k = i + 1;
while (j < sublen) {
char source = Character.toLowerCase(src.charAt(k));
if (sub.charAt(j) != source) {
continue mainloop;
}
j++; k++;
}
return i;
}
return -1;
}
/**
* Finds last index of a substring in the given source string in specified range [end, start]
* See {@link #indexOf(String, String, int, int)} for details about the speed.
*
* @param src source to examine
* @param sub substring to find
* @param startIndex starting index
* @param endIndex end index
* @return last index of founded substring or -1 if substring is not found
*/
public static int lastIndexOf(String src, String sub, int startIndex, int endIndex) {
int sublen = sub.length();
int srclen = src.length();
if (sublen == 0) {
return startIndex > srclen ? srclen : (startIndex < -1 ? -1 : startIndex);
}
int total = srclen - sublen;
if (total < 0) {
return -1;
}
if (startIndex >= total) {
startIndex = total;
}
if (endIndex < 0) {
endIndex = 0;
}
char c = sub.charAt(0);
mainloop:
for (int i = startIndex; i >= endIndex; i--) {
if (src.charAt(i) != c) {
continue;
}
int j = 1;
int k = i + 1;
while (j < sublen) {
if (sub.charAt(j) != src.charAt(k)) {
continue mainloop;
}
j++; k++;
}
return i;
}
return -1;
}
/**
* Finds last index of a character in the given source string in specified range [end, start]
*/
public static int lastIndexOf(String src, char c, int startIndex, int endIndex) {
int total = src.length() - 1;
if (total < 0) {
return -1;
}
if (startIndex >= total) {
startIndex = total;
}
if (endIndex < 0) {
endIndex = 0;
}
for (int i = startIndex; i >= endIndex; i--) {
if (src.charAt(i) == c) {
return i;
}
}
return -1;
}
/**
* Finds last index of a character in the given source string in specified range [end, start]
*/
public static int lastIndexOfIgnoreCase(String src, char c, int startIndex, int endIndex) {
int total = src.length() - 1;
if (total < 0) {
return -1;
}
if (startIndex >= total) {
startIndex = total;
}
if (endIndex < 0) {
endIndex = 0;
}
c = Character.toLowerCase(c);
for (int i = startIndex; i >= endIndex; i--) {
if (Character.toLowerCase(src.charAt(i)) == c) {
return i;
}
}
return -1;
}
/**
* Tests if this string starts with the specified prefix with ignored case.
*
* @param src source string to test
* @param subS starting substring
*
* @return <code>true</code> if the character sequence represented by the argument is
* a prefix of the character sequence represented by this string;
* <code>false</code> otherwise.
*/
public static boolean startsWithIgnoreCase(String src, String subS) {
return startsWithIgnoreCase(src, subS, 0);
}
/**
* Tests if this string starts with the specified prefix with ignored case
* and with the specified prefix beginning a specified index.
*
* @param src source string to test
* @param subS starting substring
* @param startIndex index from where to test
*
* @return <code>true</code> if the character sequence represented by the argument is
* a prefix of the character sequence represented by this string;
* <code>false</code> otherwise.
*/
public static boolean startsWithIgnoreCase(String src, String subS, int startIndex) {
String sub = subS.toLowerCase();
int sublen = sub.length();
if (startIndex + sublen > src.length()) {
return false;
}
int j = 0;
int i = startIndex;
while (j < sublen) {
char source = Character.toLowerCase(src.charAt(i));
if (sub.charAt(j) != source) {
return false;
}
j++; i++;
}
return true;
}
/**
* Tests if this string ends with the specified suffix.
*
* @param src String to test
* @param subS suffix
*
* @return <code>true</code> if the character sequence represented by the argument is
* a suffix of the character sequence represented by this object;
* <code>false</code> otherwise.
*/
public static boolean endsWithIgnoreCase(String src, String subS) {
String sub = subS.toLowerCase();
int sublen = sub.length();
int j = 0;
int i = src.length() - sublen;
if (i < 0) {
return false;
}
while (j < sublen) {
char source = Character.toLowerCase(src.charAt(i));
if (sub.charAt(j) != source) {
return false;
}
j++; i++;
}
return true;
}
// ---------------------------------------------------------------- count substrings
/**
* Counts substring occurrences in a source string.
*
* @param source source string
* @param sub substring to count
* @return number of substring occurrences
*/
public static int count(String source, String sub) {
return count(source, sub, 0);
}
public static int count(String source, String sub, int start) {
int count = 0;
int j = start;
int sublen = sub.length();
if (sublen == 0) {
return 0;
}
while (true) {
int i = source.indexOf(sub, j);
if (i == -1) {
break;
}
count++;
j = i + sublen;
}
return count;
}
public static int count(String source, char c) {
return count(source, c, 0);
}
public static int count(String source, char c, int start) {
int count = 0;
int j = start;
while (true) {
int i = source.indexOf(c, j);
if (i == -1) {
break;
}
count++;
j = i + 1;
}
return count;
}
/**
* Count substring occurrences in a source string, ignoring case.
*
* @param source source string
* @param sub substring to count
* @return number of substring occurrences
*/
public static int countIgnoreCase(String source, String sub) {
int count = 0;
int j = 0;
int sublen = sub.length();
if (sublen == 0) {
return 0;
}
while (true) {
int i = indexOfIgnoreCase(source, sub, j);
if (i == -1) {
break;
}
count++;
j = i + sublen;
}
return count;
}
// ---------------------------------------------------------------- string arrays
/**
* Finds the very first index of a substring from the specified array. It
* returns an int[2] where int[0] represents the substring index and int[1]
* represents position where substring was found. Returns <code>null</code> if
* noting found.
*
* @param s source string
* @param arr string array
*/
public static int[] indexOf(String s, String arr[]) {
return indexOf(s, arr, 0);
}
/**
* Finds the very first index of a substring from the specified array. It
* returns an int[2] where int[0] represents the substring index and int[1]
* represents position where substring was found. Returns <code>null</code>
* if noting found.
*
* @param s source string
* @param arr string array
* @param start starting position
*/
public static int[] indexOf(String s, String arr[], int start) {
int arrLen = arr.length;
int index = Integer.MAX_VALUE;
int last = -1;
for (int j = 0; j < arrLen; j++) {
int i = s.indexOf(arr[j], start);
if (i != -1) {
if (i < index) {
index = i;
last = j;
}
}
}
return last == -1 ? null : new int[] {last, index};
}
/**
* Finds the very first index of a substring from the specified array. It
* returns an int[2] where int[0] represents the substring index and int[1]
* represents position where substring was found. Returns <code>null</code>
* if noting found.
*
* @param s source string
* @param arr string array
*/
public static int[] indexOfIgnoreCase(String s, String arr[]) {
return indexOfIgnoreCase(s, arr, 0);
}
/**
* Finds the very first index of a substring from the specified array. It
* returns an int[2] where int[0] represents the substring index and int[1]
* represents position where substring was found. Returns <code>null</code>
* if noting found.
*
* @param s source string
* @param arr string array
* @param start starting position
*/
public static int[] indexOfIgnoreCase(String s, String arr[], int start) {
int arrLen = arr.length;
int index = Integer.MAX_VALUE;
int last = -1;
for (int j = 0; j < arrLen; j++) {
int i = indexOfIgnoreCase(s, arr[j], start);
if (i != -1) {
if (i < index) {
index = i;
last = j;
}
}
}
return last == -1 ? null : new int[] {last, index};
}
/**
* Finds the very last index of a substring from the specified array. It
* returns an int[2] where int[0] represents the substring index and int[1]
* represents position where substring was found. Returns <code>null</code>
* if noting found.
*
* @param s source string
* @param arr string array
*/
public static int[] lastIndexOf(String s, String arr[]) {
return lastIndexOf(s, arr, s.length());
}
/**
* Finds the very last index of a substring from the specified array. It
* returns an int[2] where int[0] represents the substring index and int[1]
* represents position where substring was found. Returns <code>null</code>
* if noting found.
*
* @param s source string
* @param arr string array
* @param fromIndex starting position
*/
public static int[] lastIndexOf(String s, String arr[], int fromIndex) {
int arrLen = arr.length;
int index = -1;
int last = -1;
for (int j = 0; j < arrLen; j++) {
int i = s.lastIndexOf(arr[j], fromIndex);
if (i != -1) {
if (i > index) {
index = i;
last = j;
}
}
}
return last == -1 ? null : new int[] {last, index};
}
/**
* Finds the very last index of a substring from the specified array. It
* returns an int[2] where int[0] represents the substring index and int[1]
* represents position where substring was found. Returns <code>null</code>
* if noting found.
*
* @param s source string
* @param arr string array
*
* @return int[2]
*/
public static int[] lastIndexOfIgnoreCase(String s, String arr[]) {
return lastIndexOfIgnoreCase(s, arr, s.length());
}
/**
* Finds the very last index of a substring from the specified array. It
* returns an int[2] where int[0] represents the substring index and int[1]
* represents position where substring was found. Returns <code>null</code>
* if noting found.
*
* @param s source string
* @param arr string array
* @param fromIndex starting position
*/
public static int[] lastIndexOfIgnoreCase(String s, String arr[], int fromIndex) {
int arrLen = arr.length;
int index = -1;
int last = -1;
for (int j = 0; j < arrLen; j++) {
int i = lastIndexOfIgnoreCase(s, arr[j], fromIndex);
if (i != -1) {
if (i > index) {
index = i;
last = j;
}
}
}
return last == -1 ? null : new int[] {last, index};
}
/**
* Compares two string arrays.
*
* @param as first string array
* @param as1 second string array
*
* @return <code>true</code> if all array elements matches
*/
public static boolean equals(String as[], String as1[]) {
if (as.length != as1.length) {
return false;
}
for (int i = 0; i < as.length; i++) {
if (as[i].equals(as1[i]) == false) {
return false;
}
}
return true;
}
/**
* Compares two string arrays.
*
* @param as first string array
* @param as1 second string array
*
* @return true if all array elements matches
*/
public static boolean equalsIgnoreCase(String as[], String as1[]) {
if (as.length != as1.length) {
return false;
}
for (int i = 0; i < as.length; i++) {
if (as[i].equalsIgnoreCase(as1[i]) == false) {
return false;
}
}
return true;
}
/**
* Replaces many substring at once. Order of string array is important.
*
* @param s source string
* @param sub substrings array
* @param with replace with array
*
* @return string with all occurrences of substrings replaced
*/
public static String replace(String s, String[] sub, String[] with) {
if ((sub.length != with.length) || (sub.length == 0)) {
return s;
}
int start = 0;
StringBuilder buf = new StringBuilder(s.length());
while (true) {
int[] res = indexOf(s, sub, start);
if (res == null) {
break;
}
int end = res[1];
buf.append(s.substring(start, end));
buf.append(with[res[0]]);
start = end + sub[res[0]].length();
}
buf.append(s.substring(start));
return buf.toString();
}
/**
* Replaces many substring at once. Order of string array is important.
*
* @param s source string
* @param sub substrings array
* @param with replace with array
*
* @return string with all occurrences of substrings replaced
*/
public static String replaceIgnoreCase(String s, String[] sub, String[] with) {
if ((sub.length != with.length) || (sub.length == 0)) {
return s;
}
int start = 0;
StringBuilder buf = new StringBuilder(s.length());
while (true) {
int[] res = indexOfIgnoreCase(s, sub, start);
if (res == null) {
break;
}
int end = res[1];
buf.append(s.substring(start, end));
buf.append(with[res[0]]);
start = end + sub[0].length();
}
buf.append(s.substring(start));
return buf.toString();
}
// ---------------------------------------------------------------- the one
/**
* Compares string with at least one from the provided array.
* If at least one equal string is found, returns its index.
* Otherwise, <code>-1</code> is returned.
*/
public static int equalsOne(String src, String[] dest) {
for (int i = 0; i < dest.length; i++) {
if (src.equals(dest[i])) {
return i;
}
}
return -1;
}
/**
* Compares string with at least one from the provided array, ignoring case.
* If at least one equal string is found, it returns its index.
* Otherwise, <code>-1</code> is returned.
*/
public static int equalsOneIgnoreCase(String src, String[] dest) {
for (int i = 0; i < dest.length; i++) {
if (src.equalsIgnoreCase(dest[i])) {
return i;
}
}
return -1;
}
/**
* Checks if string starts with at least one string from the provided array.
* If at least one string is matched, it returns its index.
* Otherwise, <code>-1</code> is returned.
*/
public static int startsWithOne(String src, String[] dest) {
for (int i = 0; i < dest.length; i++) {
if (src.startsWith(dest[i])) {
return i;
}
}
return -1;
}
/**
* Checks if string starts with at least one string from the provided array.
* If at least one string is matched, it returns its index.
* Otherwise, <code>-1</code> is returned.
*/
public static int startsWithOneIgnoreCase(String src, String[] dest) {
for (int i = 0; i < dest.length; i++) {
if (startsWithIgnoreCase(src, dest[i])) {
return i;
}
}
return -1;
}
/**
* Checks if string ends with at least one string from the provided array.
* If at least one string is matched, it returns its index.
* Otherwise, <code>-1</code> is returned.
*/
public static int endsWithOne(String src, String[] dest) {
for (int i = 0; i < dest.length; i++) {
if (src.endsWith(dest[i])) {
return i;
}
}
return -1;
}
/**
* Checks if string ends with at least one string from the provided array.
* If at least one string is matched, it returns its index.
* Otherwise, <code>-1</code> is returned.
*/
public static int endsWithOneIgnoreCase(String src, String[] dest) {
for (int i = 0; i < dest.length; i++) {
if (endsWithIgnoreCase(src, dest[i])) {
return i;
}
}
return -1;
}
// ---------------------------------------------------------------- char based
public static int indexOfChars(String string, String chars) {
return indexOfChars(string, chars, 0);
}
/**
* Returns the very first index of any char from provided string, starting from specified index offset.
* Returns index of founded char, or <code>-1</code> if nothing found.
*/
public static int indexOfChars(String string, String chars, int startindex) {
int stringLen = string.length();
int charsLen = chars.length();
if (startindex < 0) {
startindex = 0;
}
for (int i = startindex; i < stringLen; i++) {
char c = string.charAt(i);
for (int j = 0; j < charsLen; j++) {
if (c == chars.charAt(j)) {
return i;
}
}
}
return -1;
}
public static int indexOfChars(String string, char[] chars) {
return indexOfChars(string, chars, 0);
}
/**
* Returns the very first index of any char from provided string, starting from specified index offset.
* Returns index of founded char, or <code>-1</code> if nothing found.
*/
public static int indexOfChars(String string, char[] chars, int startindex) {
int stringLen = string.length();
int charsLen = chars.length;
for (int i = startindex; i < stringLen; i++) {
char c = string.charAt(i);
for (int j = 0; j < charsLen; j++) {
if (c == chars[j]) {
return i;
}
}
}
return -1;
}
// ---------------------------------------------------------------- strip
/**
* Strips leading char if string starts with one.
*/
public static String stripLeadingChar(String string, char c) {
if (string.length() > 0) {
if (string.charAt(0) == c) {
return string.substring(1);
}
}
return string;
}
/**
* Strips trailing char if string ends with one.
*/
protected String stripTrailingChar(String string, char c) {
if (string.length() > 0) {
if (string.charAt(string.length() - 1) == c) {
return string.substring(0, string.length() - 1);
}
}
return string;
}
// ---------------------------------------------------------------- trim
/**
* Trims array of strings. Null elements of the array are ignored.
*/
public static void trim(String[] strings) {
for (int i = 0; i < strings.length; i++) {
String string = strings[i];
if (string != null) {
strings[i] = string.trim();
}
}
}
/**
* Trims array of strings where empty strings are nulled.
* Null elements of the array are ignored.
* @see #trimNonEmpty(String)
*/
public static void trimNonEmpty(String[] strings) {
for (int i = 0; i < strings.length; i++) {
String string = strings[i];
if (string != null) {
strings[i] = trimNonEmpty(strings[i]);
}
}
}
/**
* Trims string where empty strings are returned as a <code>null</code>.
*/
public static String trimNonEmpty(String string) {
if (string != null) {
string = string.trim();
if (string.length() == 0) {
string = null;
}
}
return string;
}
// ---------------------------------------------------------------- regions
/**
* @see #indexOfRegion(String, String, String, int)
*/
public static int[] indexOfRegion(String string, String leftBoundary, String rightBoundary) {
return indexOfRegion(string, leftBoundary, rightBoundary, 0);
}
/**
* Returns indexes of the first region without escaping character.
* @see #indexOfRegion(String, String, String, char, int)
*/
public static int[] indexOfRegion(String string, String leftBoundary, String rightBoundary, int offset) {
int ndx = offset;
int[] res = new int[4];
ndx = string.indexOf(leftBoundary, ndx);
if (ndx == -1) {
return null;
}
res[0] = ndx;
ndx += leftBoundary.length();
res[1] = ndx;
ndx = string.indexOf(rightBoundary, ndx);
if (ndx == -1) {
return null;
}
res[2] = ndx;
res[3] = ndx + rightBoundary.length();
return res;
}
/**
* @see #indexOfRegion(String, String, String, char, int)
*/
public static int[] indexOfRegion(String string, String leftBoundary, String rightBoundary, char escape) {
return indexOfRegion(string, leftBoundary, rightBoundary, escape, 0);
}
/**
* Returns indexes of the first string region. Region is defined by its left and right boundary.
* Return value is an array of the following indexes:
* <ul>
* <li>start of left boundary index</li>
* <li>region start index, i.e. end of left boundary</li>
* <li>region end index, i.e. start of right boundary</li>
* <li>end of right boundary index</li>
* </ul>
* <p>
* Escape character may be used to prefix boundaries so they can be ignored.
* If region is not founded, <code>null</code> is returned.
*/
public static int[] indexOfRegion(String string, String leftBoundary, String rightBoundary, char escape, int offset) {
int ndx = offset;
int[] res = new int[4];
while (true) {
ndx = string.indexOf(leftBoundary, ndx);
if (ndx == -1) {
return null;
}
if (ndx > 0) {
if (string.charAt(ndx - 1) == escape) {
ndx += leftBoundary.length();
continue;
}
}
res[0] = ndx;
ndx += leftBoundary.length();
res[1] = ndx;
while (true) {
ndx = string.indexOf(rightBoundary, ndx);
if (ndx == -1) {
return null;
}
if (ndx > 0) {
if (string.charAt(ndx - 1) == escape) {
ndx += rightBoundary.length();
continue;
}
}
res[2] = ndx;
res[3] = ndx + rightBoundary.length();
return res;
}
}
}
// ---------------------------------------------------------------- join
/**
* Joins array of strings into one string.
*/
public String join(String... parts) {
StringBuilder sb = new StringBuilder();
for (String part : parts) {
sb.append(part);
}
return sb.toString();
}
// ---------------------------------------------------------------- charset
/**
* Converts string charsets.
*/
public static String convertCharset(String source, String srcCharsetName, String newCharsetName) throws UnsupportedEncodingException {
return new String(source.getBytes(srcCharsetName), newCharsetName);
}
// ---------------------------------------------------------------- chars
/**
* Safely compares provided char with char on given location.
*/
public static boolean isCharAtEqual(String string, int index, char charToCompare) {
if ((index < 0) || (index >= string.length())) {
return false;
}
return string.charAt(index) == charToCompare;
}
// ---------------------------------------------------------------- surround
/**
* @see #surround(String, String, String)
*/
public static String surround(String string, String fix) {
return surround(string, fix, fix);
}
/**
* Surrounds the string with provided prefix and suffix if such missing from string.
*/
public static String surround(String string, String prefix, String suffix) {
if (string.startsWith(prefix) == false) {
string = prefix + string;
}
if (string.endsWith(suffix) == false) {
string += suffix;
}
return string;
}
/**
* Inserts prefix if doesn"t exist.
*/
public static String prefix(String string, String prefix) {
if (string.startsWith(prefix) == false) {
string = prefix + string;
}
return string;
}
/**
* Appends suffix if doesn"t exist.
*/
public static String suffix(String string, String suffix) {
if (string.endsWith(suffix) == false) {
string += suffix;
}
return string;
}
// ---------------------------------------------------------------- cut
/**
* Cuts the string from beginning to the first index of provided substring.
*/
public static String cutFromIndexOf(String string, String substring) {
int i = string.indexOf(substring);
if (i != -1) {
string = string.substring(0, i);
}
return string;
}
public static String cutFromIndexOf(String string, char c) {
int i = string.indexOf(c);
if (i != -1) {
string = string.substring(0, i);
}
return string;
}
public static String cutToIndexOf(String string, String substring) {
int i = string.indexOf(substring);
if (i != -1) {
string = string.substring(i);
}
return string;
}
public static String cutToIndexOf(String string, char c) {
int i = string.indexOf(c);
if (i != -1) {
string = string.substring(i);
}
return string;
}
/**
* Cuts prefix if exists.
*/
public static String cutPreffix(String string, String prefix) {
if (string.startsWith(prefix)) {
string = string.substring(prefix.length());
}
return string;
}
/**
* Cuts sufix if exists.
*/
public static String cutSuffix(String string, String suffix) {
if (string.endsWith(suffix)) {
string = string.substring(0, string.length() - suffix.length());
}
return string;
}
/**
* @see #cutSurrounding(String, String, String)
*/
public static String cutSurrounding(String string, String fix) {
return cutSurrounding(string, fix, fix);
}
/**
* Removes surrounding prefix and suffixes.
*/
public static String cutSurrounding(String string, String prefix, String suffix) {
int start = 0;
int end = string.length();
if (string.startsWith(prefix)) {
start = prefix.length();
}
if (string.endsWith(suffix)) {
end -= suffix.length();
}
return string.substring(start, end);
}
/**
* Cuts the last word from the string.
*/
public static String cutLastWord(String string) {
return cutLastWord(string, false);
}
/**
* Cuts the last word from the string, but not if it is a first.
*/
public static String cutLastWordNotFirst(String string) {
return cutLastWord(string, true);
}
private static String cutLastWord(String string, boolean preserveFirst) {
int ndx = string.length() - 1;
while (ndx >= 0) {
if (Character.isUpperCase(string.charAt(ndx)) == true) {
break;
}
ndx--;
}
if (ndx >= 0) {
if ((ndx == 0) && (preserveFirst == true)) {
return string;
}
string = string.substring(0, ndx);
}
return string;
}
}
//Copyright (c) 2003-2009, Jodd Team (jodd.org). All Rights Reserved.
/**
* Various character and character sequence utilities.
*/
class CharUtil {
// ---------------------------------------------------------------- to byte array
/**
* Converts char array into byte array by stripping high byte.
*/
public static byte[] toByteArray(char[] carr) {
if (carr == null) {
return null;
}
byte[] barr = new byte[carr.length];
for (int i = 0; i < carr.length; i++) {
barr[i] = (byte) carr[i];
}
return barr;
}
/**
* Converts char array to byte array using provided encoding.
*/
public static byte[] toByteArray(char[] carr, String charset) throws UnsupportedEncodingException {
return new String(carr).getBytes(charset);
}
/**
* Converts char array into ASCII array.
* @see #toAscii(char)
*/
public static byte[] toAsciiArray(char[] carr) {
if (carr == null) {
return null;
}
byte[] barr = new byte[carr.length];
for (int i = 0; i < carr.length; i++) {
barr[i] = (byte) toAscii(carr[i]);
}
return barr;
}
/**
* Converts char sequence into byte array. Chars are truncated to byte size.
*/
public static byte[] toByteArray(CharSequence charSequence) {
if (charSequence == null) {
return null;
}
byte[] barr = new byte[charSequence.length()];
for (int i = 0; i < barr.length; i++) {
barr[i] = (byte) charSequence.charAt(i);
}
return barr;
}
/**
* Converts char sequence into ASCII array.
*/
public static byte[] toAsciiArray(CharSequence charSequence) {
if (charSequence == null) {
return null;
}
byte[] barr = new byte[charSequence.length()];
for (int i = 0; i < barr.length; i++) {
barr[i] = (byte) toAscii(charSequence.charAt(i));
}
return barr;
}
// ---------------------------------------------------------------- to char array
/**
* Converts byte array to char array by simply extending.
*/
public static char[] toCharArray(byte[] barr) {
if (barr == null) {
return null;
}
char[] carr = new char[barr.length];
for (int i = 0; i < barr.length; i++) {
carr[i] = (char) barr[i];
}
return carr;
}
/**
* Converts byte array of specific encoding to char array.
*/
public static char[] toCharArray(byte[] barr, String charset) throws UnsupportedEncodingException {
return new String(barr, charset).toCharArray();
}
/**
* Returns ASCII value of a char. In case of overload, 0x3F is returned.
*/
public static int toAscii(char c) {
if (c <= 0xFF) {
return c;
} else {
return 0x3F;
}
}
// ---------------------------------------------------------------- find
/**
* Match if one character equals to any of the given character.
*
* @return <code>true</code> if characters match any character from given array,
* otherwise <code>false</code>
*/
public static boolean equalsOne(char c, char[] match) {
for (char aMatch : match) {
if (c == aMatch) {
return true;
}
}
return false;
}
/**
* Finds index of the first character in given array the matches any from the
* given set of characters.
*
* @return index of matched character or -1
*/
public static int findFirstEqual(char[] source, int index, char[] match) {
for (int i = index; i < source.length; i++) {
if (equalsOne(source[i], match) == true) {
return i;
}
}
return -1;
}
/**
* Finds index of the first character in given array the matches any from the
* given set of characters.
*
* @return index of matched character or -1
*/
public static int findFirstEqual(char[] source, int index, char match) {
for (int i = index; i < source.length; i++) {
if (source[i] == match) {
return i;
}
}
return -1;
}
/**
* Finds index of the first character in given array the differs from the
* given set of characters.
*
* @return index of matched character or -1
*/
public static int findFirstDiff(char[] source, int index, char[] match) {
for (int i = index; i < source.length; i++) {
if (equalsOne(source[i], match) == false) {
return i;
}
}
return -1;
}
/**
* Finds index of the first character in given array the differs from the
* given set of characters.
*
* @return index of matched character or -1
*/
public static int findFirstDiff(char[] source, int index, char match) {
for (int i = index; i < source.length; i++) {
if (source[i] != match) {
return i;
}
}
return -1;
}
// ---------------------------------------------------------------- is char at
public static boolean isCharAtEqual(char[] source, int index, char match) {
if ((index < 0) || (index >= source.length)) {
return false;
}
return source[index] == match;
}
public static boolean isCharAtEqual(CharSequence source, int index, char match) {
if ((index < 0) || (index >= source.length())) {
return false;
}
return source.charAt(index) == match;
}
// ---------------------------------------------------------------- is
/**
* Returns <code>true</code> if character is a white space.
* White space definition is taken from String class (see: <code>trim()</code>
*/
public static boolean isWhitespace(char c) {
return c <= " ";
}
/**
* Returns <code>true</code> if specified character is lowercase ASCII.
* If user uses only ASCIIs, it is much much faster.
*/
public static boolean isLowercaseLetter(char c) {
return (c >= "a") && (c <= "z");
}
/**
* Returns <code>true</code> if specified character is uppercase ASCII.
* If user uses only ASCIIs, it is much much faster.
*/
public static boolean isUppercaseLetter(char c) {
return (c >= "A") && (c <= "Z");
}
public static boolean isLetter(char c) {
return ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z"));
}
public static boolean isDigit(char c) {
return (c >= "0") && (c <= "9");
}
public static boolean isLetterOrDigit(char c) {
return isDigit(c) || isLetter(c);
}
public static boolean isWordChar(char c) {
return isDigit(c) || isLetter(c) || (c == "_");
}
public static boolean isPropertyNameChar(char c) {
return isDigit(c) || isLetter(c) || (c == "_") || (c == ".") || (c == "[") || (c == "]");
}
// ---------------------------------------------------------------- conversions
/**
* Uppers lowercase ASCII char.
*/
public static char toUpperAscii(char c) {
if (isLowercaseLetter(c)) {
c -= (char) 0x20;
}
return c;
}
/**
* Lowers uppercase ASCII char.
*/
public static char toLowerAscii(char c) {
if (isUppercaseLetter(c)) {
c += (char) 0x20;
}
return c;
}
}
Right justify string, ensuring that the string ends at the last character
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 {
/**
* Right justify the contents of the string, ensuring that the string ends at the last character. If the supplied string is
* longer than the desired width, the leading characters are removed so that the last character in the supplied string at the
* last position. If the supplied string is shorter than the desired width, the padding character is inserted one or more
* times such that the last character in the supplied string appears as the last character in the resulting string and that
* the length matches that specified.
*
* @param str the string to be right justified; if null, an empty string is used
* @param width the desired width of the string; must be positive
* @param padWithChar the character to use for padding, if needed
* @return the right justified string
*/
public static String justifyRight( String str,
final int width,
char padWithChar ) {
assert width > 0;
// Trim the leading and trailing whitespace ...
str = str != null ? str.trim() : "";
final int length = str.length();
int addChars = width - length;
if (addChars < 0) {
// truncate the first characters, keep the last
return str.subSequence(length - width, length).toString();
}
// Prepend the whitespace ...
final StringBuilder sb = new StringBuilder();
while (addChars > 0) {
sb.append(padWithChar);
--addChars;
}
// Write the content ...
sb.append(str);
return sb.toString();
}
}
String.format(): left pad a string
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<
String.format(): right pad a string
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 <
Swaps the case of a String changing upper and title case to lower case, and lower case to upper case.
/*
* 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>Swaps the case of a String changing upper and title case to
* lower case, and lower case to upper case.</p>
*
* <ul>
* <li>Upper case character converts to Lower case</li>
* <li>Title case character converts to Lower case</li>
* <li>Lower case character converts to Upper case</li>
* </ul>
*
* <p>For a word based algorithm, see {@link WordUtils#swapCase(String)}.
* A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.swapCase(null) = null
* StringUtils.swapCase("") = ""
* StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer performs a word based algorithm.
* If you only use ASCII, you will notice no change.
* That functionality is available in WordUtils.</p>
*
* @param str the String to swap case, may be null
* @return the changed String, <code>null</code> if null String input
*/
public static String swapCase(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
StringBuffer buffer = new StringBuffer(strLen);
char ch = 0;
for (int i = 0; i < strLen; i++) {
ch = str.charAt(i);
if (Character.isUpperCase(ch)) {
ch = Character.toLowerCase(ch);
} else if (Character.isTitleCase(ch)) {
ch = Character.toLowerCase(ch);
} else if (Character.isLowerCase(ch)) {
ch = Character.toUpperCase(ch);
}
buffer.append(ch);
}
return buffer.toString();
}
}
Transforms words to singular, plural, humanized (human readable), underscore, camel case, or ordinal form
/*
* 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.
* <p>
* Examples:
*
* <pre>
* 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"
* </pre>
*
* </p>
* <p>
* Note that if the {@link Object#toString()} is called on the supplied object, so this method works for non-strings, too.
* </p>
*
* @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.
* <p>
* Examples:
*
* <pre>
* 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"
* </pre>
*
* </p>
* <p>
* Note that if the {@link Object#toString()} is called on the supplied object, so this method works for non-strings, too.
* </p>
*
* @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.
* <p>
* Examples:
*
* <pre>
* inflector.lowerCamelCase("active_record") #=> "activeRecord"
* inflector.lowerCamelCase("first_name") #=> "firstName"
* inflector.lowerCamelCase("name") #=> "name"
* inflector.lowerCamelCase("the-first_name","-") #=> "theFirstName"
* </pre>
*
* </p>
*
* @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.
* <p>
* Examples:
*
* <pre>
* inflector.upperCamelCase("active_record") #=> "SctiveRecord"
* inflector.upperCamelCase("first_name") #=> "FirstName"
* inflector.upperCamelCase("name") #=> "Name"
* inflector.lowerCamelCase("the-first_name","-") #=> "TheFirstName"
* </pre>
*
* </p>
*
* @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 <code>uppercaseFirstLetter</code> argument to false,
* then this method produces lowerCamelCase. This method will also use any extra delimiter characters to identify word
* boundaries.
* <p>
* Examples:
*
* <pre>
* 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"
* </pre>
*
* </p>
*
* @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.
* <p>
* Examples:
*
* <pre>
* 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"
* </pre>
*
* </p>
*
* @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.
* <p>
* Examples:
*
* <pre>
* inflector.humanize("employee_salary") #=> "Employee salary"
* inflector.humanize("author_id") #=> "Author"
* </pre>
*
* </p>
*
* @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.
* <p>
* Examples:
*
* <pre>
* inflector.titleCase("man from the boondocks") #=> "Man From The Boondocks"
* inflector.titleCase("x-men: the last stand") #=> "X Men: The Last Stand"
* </pre>
*
* </p>
*
* @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.
* <p>
* The Java {@link Pattern regular expression processing} does not use the preprocessing directives <code>\l</code>,
* <code>\u</code>, <code>\L</code>, and <code>\U</code>. If so, such directives could be used in the replacement string
* to uppercase or lowercase the backreferences. For example, <code>\L1</code> would lowercase the first backreference, and
* <code>\u3</code> would uppercase the 3rd backreference.
* </p>
*
* @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");
}
}
Truncate the supplied string to be no more than the specified length.
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 {
/**
* Truncate the supplied string to be no more than the specified length. This method returns an empty string if the supplied
* object is null.
*
* @param obj the object from which the string is to be obtained using {@link Object#toString()}.
* @param maxLength the maximum length of the string being returned
* @return the supplied string if no longer than the maximum length, or the supplied string truncated to be no longer than the
* maximum length (including the suffix)
* @throws IllegalArgumentException if the maximum length is negative
*/
public static String truncate( Object obj,
int maxLength ) {
return truncate(obj, maxLength, null);
}
/**
* Truncate the supplied string to be no more than the specified length. This method returns an empty string if the supplied
* object is null.
*
* @param obj the object from which the string is to be obtained using {@link Object#toString()}.
* @param maxLength the maximum length of the string being returned
* @param suffix the suffix that should be added to the content if the string must be truncated, or null if the default suffix
* of "..." should be used
* @return the supplied string if no longer than the maximum length, or the supplied string truncated to be no longer than the
* maximum length (including the suffix)
* @throws IllegalArgumentException if the maximum length is negative
*/
public static String truncate( Object obj,
int maxLength,
String suffix ) {
if (obj == null || maxLength == 0) {
return "";
}
String str = obj.toString();
if (str.length() <= maxLength) return str;
if (suffix == null) suffix = "...";
int maxNumChars = maxLength - suffix.length();
if (maxNumChars < 0) {
// Then the max length is actually shorter than the suffix ...
str = suffix.substring(0, maxLength);
} else if (str.length() > maxNumChars) {
str = str.substring(0, maxNumChars) + suffix;
}
return str;
}
}
Uncapitalizes a String changing the first letter to title case as per Character.toLowerCase(char). No other letters are changed.
/*
* 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>Uncapitalizes a String changing the first letter to title case as
* per {@link Character#toLowerCase(char)}. No other letters are changed.</p>
*
* <p>For a word based algorithm, see {@link WordUtils#uncapitalize(String)}.
* A <code>null</code> input String returns <code>null</code>.</p>
*
* <pre>
* StringUtils.uncapitalize(null) = null
* StringUtils.uncapitalize("") = ""
* StringUtils.uncapitalize("Cat") = "cat"
* StringUtils.uncapitalize("CAT") = "cAT"
* </pre>
*
* @param str the String to uncapitalize, may be null
* @return the uncapitalized String, <code>null</code> 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();
}
}
Uncapitalize 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 Utils {
public static String uncapitalize(String str) {
int strLen = str.length();
if (str == null || strLen == 0) {
return str;
}
return new StringBuffer(strLen).append(Character.toLowerCase(str.charAt(0))).append(
str.substring(1)).toString();
}
}
Utilities for String formatting, manipulation, and queries
/*
* 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();
}
/**
* Split the given String into tokens.
* <P>
* This method is meant to be similar to the split
* function in other programming languages but it does
* not use regular expressions. Rather the String is
* split on a single String literal.
* <P>
* Unlike java.util.StringTokenizer which accepts
* multiple character tokens as delimiters, the delimiter
* here is a single String literal.
* <P>
* Each null token is returned as an empty String.
* Delimiters are never returned as tokens.
* <P>
* If there is no delimiter because it is either empty or
* null, the only element in the result is the original String.
* <P>
* StringHelper.split("1-2-3", "-");<br>
* result: {"1","2","3"}<br>
* StringHelper.split("-1--2-", "-");<br>
* result: {"","1","","2",""}<br>
* StringHelper.split("123", "");<br>
* result: {"123"}<br>
* StringHelper.split("1-2---3----4", "--");<br>
* result: {"1-2","-3","","4"}<br>
*
* @param s String to be split.
* @param delimiter String literal on which to split.
* @return an array of tokens.
* @throws NullPointerException if s is null.
*
* @since ostermillerutils 1.00.00
*/
public static String[] split(String s, String delimiter){
int delimiterLength;
// the next statement has the side effect of throwing a null pointer
// exception if s is null.
int stringLength = s.length();
if (delimiter == null || (delimiterLength = delimiter.length()) == 0){
// it is not inherently clear what to do if there is no delimiter
// On one hand it would make sense to return each character because
// the null String can be found between each pair of characters in
// a String. However, it can be found many times there and we don"
// want to be returning multiple null tokens.
// returning the whole String will be defined as the correct behavior
// in this instance.
return new String[] {s};
}
// a two pass solution is used because a one pass solution would
// require the possible resizing and copying of memory structures
// In the worst case it would have to be resized n times with each
// resize having a O(n) copy leading to an O(n^2) algorithm.
int count;
int start;
int end;
// Scan s and count the tokens.
count = 0;
start = 0;
while((end = s.indexOf(delimiter, start)) != -1){
count++;
start = end + delimiterLength;
}
count++;
// allocate an array to return the tokens,
// we now know how big it should be
String[] result = new String[count];
// Scan s again, but this time pick out the tokens
count = 0;
start = 0;
while((end = s.indexOf(delimiter, start)) != -1){
result[count] = (s.substring(start, end));
count++;
start = end + delimiterLength;
}
end = stringLength;
result[count] = s.substring(start, end);
return (result);
}
/**
* Split the given String into tokens. Delimiters will
* be returned as tokens.
* <P>
* This method is meant to be similar to the split
* function in other programming languages but it does
* not use regular expressions. Rather the String is
* split on a single String literal.
* <P>
* Unlike java.util.StringTokenizer which accepts
* multiple character tokens as delimiters, the delimiter
* here is a single String literal.
* <P>
* Each null token is returned as an empty String.
* Delimiters are never returned as tokens.
* <P>
* If there is no delimiter because it is either empty or
* null, the only element in the result is the original String.
* <P>
* StringHelper.split("1-2-3", "-");<br>
* result: {"1","-","2","-","3"}<br>
* StringHelper.split("-1--2-", "-");<br>
* result: {"","-","1","-","","-","2","-",""}<br>
* StringHelper.split("123", "");<br>
* result: {"123"}<br>
* StringHelper.split("1-2--3---4----5", "--");<br>
* result: {"1-2","--","3","--","-4","--","","--","5"}<br>
*
* @param s String to be split.
* @param delimiter String literal on which to split.
* @return an array of tokens.
* @throws NullPointerException if s is null.
*
* @since ostermillerutils 1.05.00
*/
public static String[] splitIncludeDelimiters(String s, String delimiter){
int delimiterLength;
// the next statement has the side effect of throwing a null pointer
// exception if s is null.
int stringLength = s.length();
if (delimiter == null || (delimiterLength = delimiter.length()) == 0){
// it is not inherently clear what to do if there is no delimiter
// On one hand it would make sense to return each character because
// the null String can be found between each pair of characters in
// a String. However, it can be found many times there and we don"
// want to be returning multiple null tokens.
// returning the whole String will be defined as the correct behavior
// in this instance.
return new String[] {s};
}
// a two pass solution is used because a one pass solution would
// require the possible resizing and copying of memory structures
// In the worst case it would have to be resized n times with each
// resize having a O(n) copy leading to an O(n^2) algorithm.
int count;
int start;
int end;
// Scan s and count the tokens.
count = 0;
start = 0;
while((end = s.indexOf(delimiter, start)) != -1){
count+=2;
start = end + delimiterLength;
}
count++;
// allocate an array to return the tokens,
// we now know how big it should be
String[] result = new String[count];
// Scan s again, but this time pick out the tokens
count = 0;
start = 0;
while((end = s.indexOf(delimiter, start)) != -1){
result[count] = (s.substring(start, end));
count++;
result[count] = delimiter;
count++;
start = end + delimiterLength;
}
end = stringLength;
result[count] = s.substring(start, end);
return (result);
}
/**
* Join all the elements of a string array into a single
* String.
* <p>
* If the given array empty an empty string
* will be returned. Null elements of the array are allowed
* and will be treated like empty Strings.
*
* @param array Array to be joined into a string.
* @return Concatenation of all the elements of the given array.
* @throws NullPointerException if array is null.
*
* @since ostermillerutils 1.05.00
*/
public static String join(String[] array){
return join(array, "");
}
/**
* Join all the elements of a string array into a single
* String.
* <p>
* If the given array empty an empty string
* will be returned. Null elements of the array are allowed
* and will be treated like empty Strings.
*
* @param array Array to be joined into a string.
* @param delimiter String to place between array elements.
* @return Concatenation of all the elements of the given array with the the delimiter in between.
* @throws NullPointerException if array or delimiter is null.
*
* @since ostermillerutils 1.05.00
*/
public static String join(String[] array, String delimiter){
// Cache the length of the delimiter
// has the side effect of throwing a NullPointerException if
// the delimiter is null.
int delimiterLength = delimiter.length();
// Nothing in the array return empty string
// has the side effect of throwing a NullPointerException if
// the array is null.
if (array.length == 0) return "";
// Only one thing in the array, return it.
if (array.length == 1){
if (array[0] == null) return "";
return array[0];
}
// Make a pass through and determine the size
// of the resulting string.
int length = 0;
for (int i=0; i<array.length; i++){
if (array[i] != null) length+=array[i].length();
if (i<array.length-1) length+=delimiterLength;
}
// Make a second pass through and concatenate everything
// into a string buffer.
StringBuffer result = new StringBuffer(length);
for (int i=0; i<array.length; i++){
if (array[i] != null) result.append(array[i]);
if (i<array.length-1) result.append(delimiter);
}
return result.toString();
}
/**
* Replace occurrences of a substring.
*
* StringHelper.replace("1-2-3", "-", "|");<br>
* result: "1|2|3"<br>
* StringHelper.replace("-1--2-", "-", "|");<br>
* result: "|1||2|"<br>
* StringHelper.replace("123", "", "|");<br>
* result: "123"<br>
* StringHelper.replace("1-2---3----4", "--", "|");<br>
* result: "1-2|-3||4"<br>
* StringHelper.replace("1-2---3----4", "--", "---");<br>
* result: "1-2----3------4"<br>
*
* @param s String to be modified.
* @param find String to find.
* @param replace String to replace.
* @return a string with all the occurrences of the string to find replaced.
* @throws NullPointerException if s is null.
*
* @since ostermillerutils 1.00.00
*/
public static String replace(String s, String find, String replace){
int findLength;
// the next statement has the side effect of throwing a null pointer
// exception if s is null.
int stringLength = s.length();
if (find == null || (findLength = find.length()) == 0){
// If there is nothing to find, we won"t try and find it.
return s;
}
if (replace == null){
// a null string and an empty string are the same
// for replacement purposes.
replace = "";
}
int replaceLength = replace.length();
// We need to figure out how long our resulting string will be.
// This is required because without it, the possible resizing
// and copying of memory structures could lead to an unacceptable runtime.
// In the worst case it would have to be resized n times with each
// resize having a O(n) copy leading to an O(n^2) algorithm.
int length;
if (findLength == replaceLength){
// special case in which we don"t need to count the replacements
// because the count falls out of the length formula.
length = stringLength;
} else {
int count;
int start;
int end;
// Scan s and count the number of times we find our target.
count = 0;
start = 0;
while((end = s.indexOf(find, start)) != -1){
count++;
start = end + findLength;
}
if (count == 0){
// special case in which on first pass, we find there is nothing
// to be replaced. No need to do a second pass or create a string buffer.
return s;
}
length = stringLength - (count * (findLength - replaceLength));
}
int start = 0;
int end = s.indexOf(find, start);
if (end == -1){
// nothing was found in the string to replace.
// we can get this if the find and replace strings
// are the same length because we didn"t check before.
// in this case, we will return the original string
return s;
}
// it looks like we actually have something to replace
// *sigh* allocate memory for it.
StringBuffer sb = new StringBuffer(length);
// Scan s and do the replacements
while (end != -1){
sb.append(s.substring(start, end));
sb.append(replace);
start = end + findLength;
end = s.indexOf(find, start);
}
end = stringLength;
sb.append(s.substring(start, end));
return (sb.toString());
}
/**
* Replaces characters that may be confused by a HTML
* parser with their equivalent character entity references.
* <p>
* Any data that will appear as text on a web page should
* be be escaped. This is especially important for data
* that comes from untrusted sources such as Internet users.
* A common mistake in CGI programming is to ask a user for
* data and then put that data on a web page. For example:<pre>
* Server: What is your name?
* User: <b>Joe<b>
* Server: Hello <b>Joe</b>, Welcome</pre>
* If the name is put on the page without checking that it doesn"t
* contain HTML code or without sanitizing that HTML code, the user
* could reformat the page, insert scripts, and control the the
* content on your web server.
* <p>
* This method will replace HTML characters such as > with their
* HTML entity reference (&gt;) so that the html parser will
* be sure to interpret them as plain text rather than HTML or script.
* <p>
* This method should be used for both data to be displayed in text
* in the html document, and data put in form elements. For example:<br>
* <code><html><body><i>This in not a &lt;tag&gt;
* in HTML</i></body></html></code><br>
* and<br>
* <code><form><input type="hidden" name="date" value="<i>This data could
* be &quot;malicious&quot;</i>"></form></code><br>
* In the second example, the form data would be properly be resubmitted
* to your CGI script in the URLEncoded format:<br>
* <code><i>This data could be %22malicious%22</i></code>
*
* @param s String to be escaped
* @return escaped String
* @throws NullPointerException if s is null.
*
* @since ostermillerutils 1.00.00
*/
public static String escapeHTML(String s){
int length = s.length();
int newLength = length;
boolean someCharacterEscaped = false;
// first check for characters that might
// be dangerous and calculate a length
// of the string that has escapes.
for (int i=0; i<length; i++){
char c = s.charAt(i);
int cint = 0xffff & c;
if (cint < 32){
switch(c){
case "\r":
case "\n":
case "\t":
case "\f":{
// Leave whitespace untouched
} break;
default: {
newLength -= 1;
someCharacterEscaped = true;
}
}
} else {
switch(c){
case "\"":{
newLength += 5;
someCharacterEscaped = true;
} break;
case "&":
case "\"":{
newLength += 4;
someCharacterEscaped = true;
} break;
case "<":
case ">":{
newLength += 3;
someCharacterEscaped = true;
} break;
}
}
}
if (!someCharacterEscaped){
// nothing to escape in the string
return s;
}
StringBuffer sb = new StringBuffer(newLength);
for (int i=0; i<length; i++){
char c = s.charAt(i);
int cint = 0xffff & c;
if (cint < 32){
switch(c){
case "\r":
case "\n":
case "\t":
case "\f":{
sb.append(c);
} break;
default: {
// Remove this character
}
}
} else {
switch(c){
case "\"":{
sb.append(""");
} break;
case "\"":{
sb.append("'");
} break;
case "&":{
sb.append("&");
} break;
case "<":{
sb.append("<");
} break;
case ">":{
sb.append(">");
} break;
default: {
sb.append(c);
}
}
}
}
return sb.toString();
}
/**
* Replaces characters that may be confused by an SQL
* parser with their equivalent escape characters.
* <p>
* Any data that will be put in an SQL query should
* be be escaped. This is especially important for data
* that comes from untrusted sources such as Internet users.
* <p>
* For example if you had the following SQL query:<br>
* <code>"SELECT * FROM addresses WHERE name="" + name + "" AND private="N""</code><br>
* Without this function a user could give <code>" OR 1=1 OR ""=""</code>
* as their name causing the query to be:<br>
* <code>"SELECT * FROM addresses WHERE name="" OR 1=1 OR ""="" AND private="N""</code><br>
* which will give all addresses, including private ones.<br>
* Correct usage would be:<br>
* <code>"SELECT * FROM addresses WHERE name="" + StringHelper.escapeSQL(name) + "" AND private="N""</code><br>
* <p>
* Another way to avoid this problem is to use a PreparedStatement
* with appropriate place holders.
*
* @param s String to be escaped
* @return escaped String
* @throws NullPointerException if s is null.
*
* @since ostermillerutils 1.00.00
*/
public static String escapeSQL(String s){
int length = s.length();
int newLength = length;
// first check for characters that might
// be dangerous and calculate a length
// of the string that has escapes.
for (int i=0; i<length; i++){
char c = s.charAt(i);
switch(c){
case "\\":
case "\"":
case "\"":
case "\0":{
newLength += 1;
} break;
}
}
if (length == newLength){
// nothing to escape in the string
return s;
}
StringBuffer sb = new StringBuffer(newLength);
for (int i=0; i<length; i++){
char c = s.charAt(i);
switch(c){
case "\\":{
sb.append("\\\\");
} break;
case "\"":{
sb.append("\\\"");
} break;
case "\"":{
sb.append("\\\"");
} break;
case "\0":{
sb.append("\\0");
} break;
default: {
sb.append(c);
}
}
}
return sb.toString();
}
/**
* Replaces characters that are not allowed in a Java style
* string literal with their escape characters. Specifically
* quote ("), single quote ("), new line (\n), carriage return (\r),
* and backslash (\), and tab (\t) are escaped.
*
* @param s String to be escaped
* @return escaped String
* @throws NullPointerException if s is null.
*
* @since ostermillerutils 1.00.00
*/
public static String escapeJavaLiteral(String s){
int length = s.length();
int newLength = length;
// first check for characters that might
// be dangerous and calculate a length
// of the string that has escapes.
for (int i=0; i<length; i++){
char c = s.charAt(i);
switch(c){
case "\"":
case "\"":
case "\n":
case "\r":
case "\t":
case "\\":{
newLength += 1;
} break;
}
}
if (length == newLength){
// nothing to escape in the string
return s;
}
StringBuffer sb = new StringBuffer(newLength);
for (int i=0; i<length; i++){
char c = s.charAt(i);
switch(c){
case "\"":{
sb.append("\\\"");
} break;
case "\"":{
sb.append("\\\"");
} break;
case "\n":{
sb.append("\\n");
} break;
case "\r":{
sb.append("\\r");
} break;
case "\t":{
sb.append("\\t");
} break;
case "\\":{
sb.append("\\\\");
} break;
default: {
sb.append(c);
}
}
}
return sb.toString();
}
/**
* 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);
}
private static HashMap<String,Integer> htmlEntities = new HashMap<String,Integer>();
static {
htmlEntities.put("n"+"b"+"s"+"p", new Integer(160));
htmlEntities.put("i"+"e"+"x"+"c"+"l", new Integer(161));
htmlEntities.put("cent", new Integer(162));
htmlEntities.put("pound", new Integer(163));
htmlEntities.put("c"+"u"+"r"+"r"+"e"+"n", new Integer(164));
htmlEntities.put("y"+"e"+"n", new Integer(165));
htmlEntities.put("b"+"r"+"v"+"b"+"a"+"r", new Integer(166));
htmlEntities.put("sect", new Integer(167));
htmlEntities.put("u"+"m"+"l", new Integer(168));
htmlEntities.put("copy", new Integer(169));
htmlEntities.put("o"+"r"+"d"+"f", new Integer(170));
htmlEntities.put("l"+"a"+"quo", new Integer(171));
htmlEntities.put("not", new Integer(172));
htmlEntities.put("shy", new Integer(173));
htmlEntities.put("r"+"e"+"g", new Integer(174));
htmlEntities.put("m"+"a"+"c"+"r", new Integer(175));
htmlEntities.put("d"+"e"+"g", new Integer(176));
htmlEntities.put("plus"+"m"+"n", new Integer(177));
htmlEntities.put("sup2", new Integer(178));
htmlEntities.put("sup3", new Integer(179));
htmlEntities.put("acute", new Integer(180));
htmlEntities.put("m"+"i"+"c"+"r"+"o", new Integer(181));
htmlEntities.put("par"+"a", new Integer(182));
htmlEntities.put("mid"+"dot", new Integer(183));
htmlEntities.put("c"+"e"+"d"+"i"+"l", new Integer(184));
htmlEntities.put("sup1", new Integer(185));
htmlEntities.put("o"+"r"+"d"+"m", new Integer(186));
htmlEntities.put("r"+"a"+"quo", new Integer(187));
htmlEntities.put("frac14", new Integer(188));
htmlEntities.put("frac12", new Integer(189));
htmlEntities.put("frac34", new Integer(190));
htmlEntities.put("i"+"quest", new Integer(191));
htmlEntities.put("A"+"grave", new Integer(192));
htmlEntities.put("A"+"a"+"cute", new Integer(193));
htmlEntities.put("A"+"c"+"i"+"r"+"c", new Integer(194));
htmlEntities.put("A"+"tilde", new Integer(195));
htmlEntities.put("A"+"u"+"m"+"l", new Integer(196));
htmlEntities.put("A"+"ring", new Integer(197));
htmlEntities.put("A"+"E"+"l"+"i"+"g", new Integer(198));
htmlEntities.put("C"+"c"+"e"+"d"+"i"+"l", new Integer(199));
htmlEntities.put("E"+"grave", new Integer(200));
htmlEntities.put("E"+"a"+"cute", new Integer(201));
htmlEntities.put("E"+"c"+"i"+"r"+"c", new Integer(202));
htmlEntities.put("E"+"u"+"m"+"l", new Integer(203));
htmlEntities.put("I"+"grave", new Integer(204));
htmlEntities.put("I"+"a"+"cute", new Integer(205));
htmlEntities.put("I"+"c"+"i"+"r"+"c", new Integer(206));
htmlEntities.put("I"+"u"+"m"+"l", new Integer(207));
htmlEntities.put("ETH", new Integer(208));
htmlEntities.put("N"+"tilde", new Integer(209));
htmlEntities.put("O"+"grave", new Integer(210));
htmlEntities.put("O"+"a"+"cute", new Integer(211));
htmlEntities.put("O"+"c"+"i"+"r"+"c", new Integer(212));
htmlEntities.put("O"+"tilde", new Integer(213));
htmlEntities.put("O"+"u"+""+"m"+"l", new Integer(214));
htmlEntities.put("times", new Integer(215));
htmlEntities.put("O"+"slash", new Integer(216));
htmlEntities.put("U"+"grave", new Integer(217));
htmlEntities.put("U"+"a"+"cute", new Integer(218));
htmlEntities.put("U"+"c"+"i"+"r"+"c", new Integer(219));
htmlEntities.put("U"+"u"+"m"+"l", new Integer(220));
htmlEntities.put("Y"+"a"+"cute", new Integer(221));
htmlEntities.put("THORN", new Integer(222));
htmlEntities.put("s"+"z"+"l"+"i"+"g", new Integer(223));
htmlEntities.put("a"+"grave", new Integer(224));
htmlEntities.put("a"+"a"+"cute", new Integer(225));
htmlEntities.put("a"+"c"+"i"+"r"+"c", new Integer(226));
htmlEntities.put("a"+"tilde", new Integer(227));
htmlEntities.put("a"+"u"+"m"+"l", new Integer(228));
htmlEntities.put("a"+"ring", new Integer(229));
htmlEntities.put("a"+"e"+"l"+"i"+"g", new Integer(230));
htmlEntities.put("c"+"c"+"e"+"d"+"i"+"l", new Integer(231));
htmlEntities.put("e"+"grave", new Integer(232));
htmlEntities.put("e"+"a"+"cute", new Integer(233));
htmlEntities.put("e"+"c"+"i"+"r"+"c", new Integer(234));
htmlEntities.put("e"+"u"+"m"+"l", new Integer(235));
htmlEntities.put("i"+"grave", new Integer(236));
htmlEntities.put("i"+"a"+"cute", new Integer(237));
htmlEntities.put("i"+"c"+"i"+"r"+"c", new Integer(238));
htmlEntities.put("i"+"u"+""+"m"+"l", new Integer(239));
htmlEntities.put("e"+"t"+"h", new Integer(240));
htmlEntities.put("n"+"tilde", new Integer(241));
htmlEntities.put("o"+"grave", new Integer(242));
htmlEntities.put("o"+"a"+"cute", new Integer(243));
htmlEntities.put("o"+"c"+"i"+"r"+"c", new Integer(244));
htmlEntities.put("o"+"tilde", new Integer(245));
htmlEntities.put("o"+"u"+"m"+"l", new Integer(246));
htmlEntities.put("divide", new Integer(247));
htmlEntities.put("o"+"slash", new Integer(248));
htmlEntities.put("u"+"grave", new Integer(249));
htmlEntities.put("u"+"a"+"cute", new Integer(250));
htmlEntities.put("u"+"c"+"i"+"r"+"c", new Integer(251));
htmlEntities.put("u"+"u"+"m"+"l", new Integer(252));
htmlEntities.put("y"+"a"+"cute", new Integer(253));
htmlEntities.put("thorn", new Integer(254));
htmlEntities.put("y"+"u"+"m"+"l", new Integer(255));
htmlEntities.put("f"+"no"+"f", new Integer(402));
htmlEntities.put("Alpha", new Integer(913));
htmlEntities.put("Beta", new Integer(914));
htmlEntities.put("Gamma", new Integer(915));
htmlEntities.put("Delta", new Integer(916));
htmlEntities.put("Epsilon", new Integer(917));
htmlEntities.put("Z"+"e"+"t"+"a", new Integer(918));
htmlEntities.put("E"+"t"+"a", new Integer(919));
htmlEntities.put("T"+"h"+"e"+"t"+"a", new Integer(920));
htmlEntities.put("I"+"o"+"t"+"a", new Integer(921));
htmlEntities.put("K"+"a"+"p"+"pa", new Integer(922));
htmlEntities.put("Lambda", new Integer(923));
htmlEntities.put("M"+"u", new Integer(924));
htmlEntities.put("N"+"u", new Integer(925));
htmlEntities.put("Xi", new Integer(926));
htmlEntities.put("O"+"m"+"i"+"c"+"r"+"on", new Integer(927));
htmlEntities.put("Pi", new Integer(928));
htmlEntities.put("R"+"h"+"o", new Integer(929));
htmlEntities.put("S"+"i"+"g"+"m"+"a", new Integer(931));
htmlEntities.put("Tau", new Integer(932));
htmlEntities.put("Up"+"s"+"i"+"l"+"on", new Integer(933));
htmlEntities.put("P"+"h"+"i", new Integer(934));
htmlEntities.put("C"+"h"+"i", new Integer(935));
htmlEntities.put("P"+"s"+"i", new Integer(936));
htmlEntities.put("O"+"m"+"e"+"g"+"a", new Integer(937));
htmlEntities.put("alpha", new Integer(945));
htmlEntities.put("beta", new Integer(946));
htmlEntities.put("gamma", new Integer(947));
htmlEntities.put("delta", new Integer(948));
htmlEntities.put("epsilon", new Integer(949));
htmlEntities.put("z"+"e"+"t"+"a", new Integer(950));
htmlEntities.put("e"+"t"+"a", new Integer(951));
htmlEntities.put("the"+"t"+"a", new Integer(952));
htmlEntities.put("i"+"o"+"t"+"a", new Integer(953));
htmlEntities.put("k"+"a"+"p"+"pa", new Integer(954));
htmlEntities.put("lambda", new Integer(955));
htmlEntities.put("m"+"u", new Integer(956));
htmlEntities.put("n"+"u", new Integer(957));
htmlEntities.put("xi", new Integer(958));
htmlEntities.put("o"+"m"+"i"+""+"c"+"r"+"on", new Integer(959));
htmlEntities.put("pi", new Integer(960));
htmlEntities.put("r"+"h"+"o", new Integer(961));
htmlEntities.put("s"+"i"+"g"+"m"+"a"+"f", new Integer(962));
htmlEntities.put("s"+"i"+"g"+"m"+"a", new Integer(963));
htmlEntities.put("tau", new Integer(964));
htmlEntities.put("up"+"s"+"i"+"l"+"on", new Integer(965));
htmlEntities.put("p"+"h"+"i", new Integer(966));
htmlEntities.put("c"+"h"+"i", new Integer(967));
htmlEntities.put("p"+"s"+"i", new Integer(968));
htmlEntities.put("o"+"m"+"e"+"g"+"a", new Integer(969));
htmlEntities.put("the"+"t"+"a"+"s"+"y"+"m", new Integer(977));
htmlEntities.put("up"+"s"+"i"+"h", new Integer(978));
htmlEntities.put("pi"+"v", new Integer(982));
htmlEntities.put("bull", new Integer(8226));
htmlEntities.put("hell"+"i"+"p", new Integer(8230));
htmlEntities.put("prime", new Integer(8242));
htmlEntities.put("Prime", new Integer(8243));
htmlEntities.put("o"+"line", new Integer(8254));
htmlEntities.put("f"+"r"+""+"a"+"s"+"l", new Integer(8260));
htmlEntities.put("we"+"i"+"e"+"r"+"p", new Integer(8472));
htmlEntities.put("image", new Integer(8465));
htmlEntities.put("real", new Integer(8476));
htmlEntities.put("trade", new Integer(8482));
htmlEntities.put("ale"+"f"+"s"+"y"+"m", new Integer(8501));
htmlEntities.put("l"+"a"+"r"+"r", new Integer(8592));
htmlEntities.put("u"+"a"+"r"+"r", new Integer(8593));
htmlEntities.put("r"+"a"+"r"+"r", new Integer(8594));
htmlEntities.put("d"+"a"+"r"+"r", new Integer(8595));
htmlEntities.put("ha"+"r"+"r", new Integer(8596));
htmlEntities.put("c"+"r"+""+"a"+"r"+"r", new Integer(8629));
htmlEntities.put("lArr", new Integer(8656));
htmlEntities.put("uArr", new Integer(8657));
htmlEntities.put("rArr", new Integer(8658));
htmlEntities.put("dArr", new Integer(8659));
htmlEntities.put("hArr", new Integer(8660));
htmlEntities.put("for"+"all", new Integer(8704));
htmlEntities.put("part", new Integer(8706));
htmlEntities.put("exist", new Integer(8707));
htmlEntities.put("empty", new Integer(8709));
htmlEntities.put("n"+"a"+"b"+"l"+"a", new Integer(8711));
htmlEntities.put("is"+"in", new Integer(8712));
htmlEntities.put("not"+"in", new Integer(8713));
htmlEntities.put("n"+"i", new Integer(8715));
htmlEntities.put("p"+"rod", new Integer(8719));
htmlEntities.put("sum", new Integer(8721));
htmlEntities.put("minus", new Integer(8722));
htmlEntities.put("low"+"as"+"t", new Integer(8727));
htmlEntities.put("r"+"a"+"d"+"i"+"c", new Integer(8730));
htmlEntities.put("prop", new Integer(8733));
htmlEntities.put("in"+"fin", new Integer(8734));
htmlEntities.put("an"+"g", new Integer(8736));
htmlEntities.put("and", new Integer(8743));
htmlEntities.put("or", new Integer(8744));
htmlEntities.put("cap", new Integer(8745));
htmlEntities.put("cup", new Integer(8746));
htmlEntities.put("int", new Integer(8747));
htmlEntities.put("there4", new Integer(8756));
htmlEntities.put("s"+"i"+"m", new Integer(8764));
htmlEntities.put("c"+"on"+"g", new Integer(8773));
htmlEntities.put("a"+"s"+"y"+"m"+"p", new Integer(8776));
htmlEntities.put("n"+"e", new Integer(8800));
htmlEntities.put("e"+"q"+"u"+"i"+"v", new Integer(8801));
htmlEntities.put("l"+"e", new Integer(8804));
htmlEntities.put("g"+"e", new Integer(8805));
htmlEntities.put("sub", new Integer(8834));
htmlEntities.put("sup", new Integer(8835));
htmlEntities.put("n"+"sub", new Integer(8836));
htmlEntities.put("sub"+"e", new Integer(8838));
htmlEntities.put("sup"+"e", new Integer(8839));
htmlEntities.put("o"+"plus", new Integer(8853));
htmlEntities.put("o"+"times", new Integer(8855));
htmlEntities.put("per"+"p", new Integer(8869));
htmlEntities.put("s"+"dot", new Integer(8901));
htmlEntities.put("l"+"c"+"e"+"i"+"l", new Integer(8968));
htmlEntities.put("r"+"c"+"e"+"i"+"l", new Integer(8969));
htmlEntities.put("l"+"floor", new Integer(8970));
htmlEntities.put("r"+"floor", new Integer(8971));
htmlEntities.put("lang", new Integer(9001));
htmlEntities.put("rang", new Integer(9002));
htmlEntities.put("l"+"o"+"z", new Integer(9674));
htmlEntities.put("spades", new Integer(9824));
htmlEntities.put("clubs", new Integer(9827));
htmlEntities.put("hearts", new Integer(9829));
htmlEntities.put("d"+"i"+"am"+"s", new Integer(9830));
htmlEntities.put("quot", new Integer(34));
htmlEntities.put("amp", new Integer(38));
htmlEntities.put("lt", new Integer(60));
htmlEntities.put("gt", new Integer(62));
htmlEntities.put("OElig", new Integer(338));
htmlEntities.put("o"+"e"+"l"+"i"+"g", new Integer(339));
htmlEntities.put("Scar"+"on", new Integer(352));
htmlEntities.put("scar"+"on", new Integer(353));
htmlEntities.put("Y"+"u"+"m"+"l", new Integer(376));
htmlEntities.put("c"+"i"+"r"+"c", new Integer(710));
htmlEntities.put("tilde", new Integer(732));
htmlEntities.put("e"+"n"+"s"+"p", new Integer(8194));
htmlEntities.put("e"+"m"+"s"+"p", new Integer(8195));
htmlEntities.put("thin"+"s"+"p", new Integer(8201));
htmlEntities.put("z"+"w"+"n"+"j", new Integer(8204));
htmlEntities.put("z"+"w"+"j", new Integer(8205));
htmlEntities.put("l"+"r"+"m", new Integer(8206));
htmlEntities.put("r"+"l"+"m", new Integer(8207));
htmlEntities.put("n"+"dash", new Integer(8211));
htmlEntities.put("m"+"dash", new Integer(8212));
htmlEntities.put("l"+"s"+"quo", new Integer(8216));
htmlEntities.put("r"+"s"+"quo", new Integer(8217));
htmlEntities.put("s"+"b"+"quo", new Integer(8218));
htmlEntities.put("l"+"d"+"quo", new Integer(8220));
htmlEntities.put("r"+"d"+"quo", new Integer(8221));
htmlEntities.put("b"+"d"+"quo", new Integer(8222));
htmlEntities.put("dagger", new Integer(8224));
htmlEntities.put("Dagger", new Integer(8225));
htmlEntities.put("p"+"e"+"r"+"m"+"i"+"l", new Integer(8240));
htmlEntities.put("l"+"s"+"a"+"quo", new Integer(8249));
htmlEntities.put("r"+"s"+"a"+"quo", new Integer(8250));
htmlEntities.put("euro", new Integer(8364));
}
/**
* Turn any HTML escape entities in the string into
* characters and return the resulting string.
*
* @param s String to be un-escaped.
* @return un-escaped String.
* @throws NullPointerException if s is null.
*
* @since ostermillerutils 1.00.00
*/
public static String unescapeHTML(String s){
StringBuffer result = new StringBuffer(s.length());
int ampInd = s.indexOf("&");
int lastEnd = 0;
while (ampInd >= 0){
int nextAmp = s.indexOf("&", ampInd+1);
int nextSemi = s.indexOf(";", ampInd+1);
if (nextSemi != -1 && (nextAmp == -1 || nextSemi < nextAmp)){
int value = -1;
String escape = s.substring(ampInd+1,nextSemi);
try {
if (escape.startsWith("#")){
value = Integer.parseInt(escape.substring(1), 10);
} else {
if (htmlEntities.containsKey(escape)){
value = htmlEntities.get(escape).intValue();
}
}
} catch (NumberFormatException x){
// Could not parse the entity,
// output it verbatim
}
result.append(s.substring(lastEnd, ampInd));
lastEnd = nextSemi + 1;
if (value >= 0 && value <= 0xffff){
result.append((char)value);
} else {
result.append("&").append(escape).append(";");
}
}
ampInd = nextAmp;
}
result.append(s.substring(lastEnd));
return result.toString();
}
/**
* Escapes characters that have special meaning to
* regular expressions
*
* @param s String to be escaped
* @return escaped String
* @throws NullPointerException if s is null.
*
* @since ostermillerutils 1.02.25
*/
public static String escapeRegularExpressionLiteral(String s){
// According to the documentation in the Pattern class:
//
// The backslash character ("\") serves to introduce escaped constructs,
// as defined in the table above, as well as to quote characters that
// otherwise would be interpreted as un-escaped constructs. Thus the
// expression \\ matches a single backslash and \{ matches a left brace.
//
// It is an error to use a backslash prior to any alphabetic character
// that does not denote an escaped construct; these are reserved for future
// extensions to the regular-expression language. A backslash may be used
// prior to a non-alphabetic character regardless of whether that character
// is part of an un-escaped construct.
//
// As a result, escape everything except [0-9a-zA-Z]
int length = s.length();
int newLength = length;
// first check for characters that might
// be dangerous and calculate a length
// of the string that has escapes.
for (int i=0; i<length; i++){
char c = s.charAt(i);
if (!((c>="0" && c<="9") || (c>="A" && c<="Z") || (c>="a" && c<="z"))){
newLength += 1;
}
}
if (length == newLength){
// nothing to escape in the string
return s;
}
StringBuffer sb = new StringBuffer(newLength);
for (int i=0; i<length; i++){
char c = s.charAt(i);
if (!((c>="0" && c<="9") || (c>="A" && c<="Z") || (c>="a" && c<="z"))){
sb.append("\\");
}
sb.append(c);
}
return sb.toString();
}
/**
* Build a regular expression that is each of the terms or"d together.
*
* @param terms a list of search terms.
* @param sb place to build the regular expression.
* @throws IllegalArgumentException if the length of terms is zero.
*
* @since ostermillerutils 1.02.25
*/
private static void buildFindAnyPattern(String[] terms, StringBuffer sb){
if (terms.length == 0) throw new IllegalArgumentException("There must be at least one term to find.");
sb.append("(?:");
for (int i=0; i<terms.length; i++){
if (i>0) sb.append("|");
sb.append("(?:");
sb.append(escapeRegularExpressionLiteral(terms[i]));
sb.append(")");
}
sb.append(")");
}
/**
* Compile a pattern that can will match a string if the string
* contains any of the given terms.
* <p>
* Usage:<br>
* <code>boolean b = getContainsAnyPattern(terms).matcher(s).matches();</code>
* <p>
* If multiple strings are matched against the same set of terms,
* it is more efficient to reuse the pattern returned by this function.
*
* @param terms Array of search strings.
* @return Compiled pattern that can be used to match a string to see if it contains any of the terms.
*
* @since ostermillerutils 1.02.25
*/
public static Pattern getContainsAnyPattern(String[] terms){
StringBuffer sb = new StringBuffer();
sb.append("(?s).*");
buildFindAnyPattern(terms, sb);
sb.append(".*");
return Pattern.rupile(sb.toString());
}
/**
* Compile a pattern that can will match a string if the string
* equals any of the given terms.
* <p>
* Usage:<br>
* <code>boolean b = getEqualsAnyPattern(terms).matcher(s).matches();</code>
* <p>
* If multiple strings are matched against the same set of terms,
* it is more efficient to reuse the pattern returned by this function.
*
* @param terms Array of search strings.
* @return Compiled pattern that can be used to match a string to see if it equals any of the terms.
*
* @since ostermillerutils 1.02.25
*/
public static Pattern getEqualsAnyPattern(String[] terms){
StringBuffer sb = new StringBuffer();
sb.append("(?s)\\A");
buildFindAnyPattern(terms, sb);
sb.append("\\z");
return Pattern.rupile(sb.toString());
}
/**
* Compile a pattern that can will match a string if the string
* starts with any of the given terms.
* <p>
* Usage:<br>
* <code>boolean b = getStartsWithAnyPattern(terms).matcher(s).matches();</code>
* <p>
* If multiple strings are matched against the same set of terms,
* it is more efficient to reuse the pattern returned by this function.
*
* @param terms Array of search strings.
* @return Compiled pattern that can be used to match a string to see if it starts with any of the terms.
*
* @since ostermillerutils 1.02.25
*/
public static Pattern getStartsWithAnyPattern(String[] terms){
StringBuffer sb = new StringBuffer();
sb.append("(?s)\\A");
buildFindAnyPattern(terms, sb);
sb.append(".*");
return Pattern.rupile(sb.toString());
}
/**
* Compile a pattern that can will match a string if the string
* ends with any of the given terms.
* <p>
* Usage:<br>
* <code>boolean b = getEndsWithAnyPattern(terms).matcher(s).matches();</code>
* <p>
* If multiple strings are matched against the same set of terms,
* it is more efficient to reuse the pattern returned by this function.
*
* @param terms Array of search strings.
* @return Compiled pattern that can be used to match a string to see if it ends with any of the terms.
*
* @since ostermillerutils 1.02.25
*/
public static Pattern getEndsWithAnyPattern(String[] terms){
StringBuffer sb = new StringBuffer();
sb.append("(?s).*");
buildFindAnyPattern(terms, sb);
sb.append("\\z");
return Pattern.rupile(sb.toString());
}
/**
* Compile a pattern that can will match a string if the string
* contains any of the given terms.
* <p>
* Case is ignored when matching using Unicode case rules.
* <p>
* Usage:<br>
* <code>boolean b = getContainsAnyPattern(terms).matcher(s).matches();</code>
* <p>
* If multiple strings are matched against the same set of terms,
* it is more efficient to reuse the pattern returned by this function.
*
* @param terms Array of search strings.
* @return Compiled pattern that can be used to match a string to see if it contains any of the terms.
*
* @since ostermillerutils 1.02.25
*/
public static Pattern getContainsAnyIgnoreCasePattern(String[] terms){
StringBuffer sb = new StringBuffer();
sb.append("(?i)(?u)(?s).*");
buildFindAnyPattern(terms, sb);
sb.append(".*");
return Pattern.rupile(sb.toString());
}
/**
* Compile a pattern that can will match a string if the string
* equals any of the given terms.
* <p>
* Case is ignored when matching using Unicode case rules.
* <p>
* Usage:<br>
* <code>boolean b = getEqualsAnyPattern(terms).matcher(s).matches();</code>
* <p>
* If multiple strings are matched against the same set of terms,
* it is more efficient to reuse the pattern returned by this function.
*
* @param terms Array of search strings.
* @return Compiled pattern that can be used to match a string to see if it equals any of the terms.
*
* @since ostermillerutils 1.02.25
*/
public static Pattern getEqualsAnyIgnoreCasePattern(String[] terms){
StringBuffer sb = new StringBuffer();
sb.append("(?i)(?u)(?s)\\A");
buildFindAnyPattern(terms, sb);
sb.append("\\z");
return Pattern.rupile(sb.toString());
}
/**
* Compile a pattern that can will match a string if the string
* starts with any of the given terms.
* <p>
* Case is ignored when matching using Unicode case rules.
* <p>
* Usage:<br>
* <code>boolean b = getStartsWithAnyPattern(terms).matcher(s).matches();</code>
* <p>
* If multiple strings are matched against the same set of terms,
* it is more efficient to reuse the pattern returned by this function.
*
* @param terms Array of search strings.
* @return Compiled pattern that can be used to match a string to see if it starts with any of the terms.
*
* @since ostermillerutils 1.02.25
*/
public static Pattern getStartsWithAnyIgnoreCasePattern(String[] terms){
StringBuffer sb = new StringBuffer();
sb.append("(?i)(?u)(?s)\\A");
buildFindAnyPattern(terms, sb);
sb.append(".*");
return Pattern.rupile(sb.toString());
}
/**
* Compile a pattern that can will match a string if the string
* ends with any of the given terms.
* <p>
* Case is ignored when matching using Unicode case rules.
* <p>
* Usage:<br>
* <code>boolean b = getEndsWithAnyPattern(terms).matcher(s).matches();</code>
* <p>
* If multiple strings are matched against the same set of terms,
* it is more efficient to reuse the pattern returned by this function.
*
* @param terms Array of search strings.
* @return Compiled pattern that can be used to match a string to see if it ends with any of the terms.
*
* @since ostermillerutils 1.02.25
*/
public static Pattern getEndsWithAnyIgnoreCasePattern(String[] terms){
StringBuffer sb = new StringBuffer();
sb.append("(?i)(?u)(?s).*");
buildFindAnyPattern(terms, sb);
sb.append("\\z");
return Pattern.rupile(sb.toString());
}
/**
* Tests to see if the given string contains any of the given terms.
* <p>
* This implementation is more efficient than the brute force approach
* of testing the string against each of the terms. It instead compiles
* a single regular expression that can test all the terms at once, and
* uses that expression against the string.
* <p>
* This is a convenience method. If multiple strings are tested against
* the same set of terms, it is more efficient not to compile the regular
* expression multiple times.
* @see #getContainsAnyPattern(String[])
*
* @param s String that may contain any of the given terms.
* @param terms list of substrings that may be contained in the given string.
* @return true iff one of the terms is a substring of the given string.
*
* @since ostermillerutils 1.02.25
*/
public static boolean containsAny(String s, String[] terms){
return getContainsAnyPattern(terms).matcher(s).matches();
}
/**
* Tests to see if the given string equals any of the given terms.
* <p>
* This implementation is more efficient than the brute force approach
* of testing the string against each of the terms. It instead compiles
* a single regular expression that can test all the terms at once, and
* uses that expression against the string.
* <p>
* This is a convenience method. If multiple strings are tested against
* the same set of terms, it is more efficient not to compile the regular
* expression multiple times.
* @see #getEqualsAnyPattern(String[])
*
* @param s String that may equal any of the given terms.
* @param terms list of strings that may equal the given string.
* @return true iff one of the terms is equal to the given string.
*
* @since ostermillerutils 1.02.25
*/
public static boolean equalsAny(String s, String[] terms){
return getEqualsAnyPattern(terms).matcher(s).matches();
}
/**
* Tests to see if the given string starts with any of the given terms.
* <p>
* This implementation is more efficient than the brute force approach
* of testing the string against each of the terms. It instead compiles
* a single regular expression that can test all the terms at once, and
* uses that expression against the string.
* <p>
* This is a convenience method. If multiple strings are tested against
* the same set of terms, it is more efficient not to compile the regular
* expression multiple times.
* @see #getStartsWithAnyPattern(String[])
*
* @param s String that may start with any of the given terms.
* @param terms list of strings that may start with the given string.
* @return true iff the given string starts with one of the given terms.
*
* @since ostermillerutils 1.02.25
*/
public static boolean startsWithAny(String s, String[] terms){
return getStartsWithAnyPattern(terms).matcher(s).matches();
}
/**
* Tests to see if the given string ends with any of the given terms.
* <p>
* This implementation is more efficient than the brute force approach
* of testing the string against each of the terms. It instead compiles
* a single regular expression that can test all the terms at once, and
* uses that expression against the string.
* <p>
* This is a convenience method. If multiple strings are tested against
* the same set of terms, it is more efficient not to compile the regular
* expression multiple times.
* @see #getEndsWithAnyPattern(String[])
*
* @param s String that may end with any of the given terms.
* @param terms list of strings that may end with the given string.
* @return true iff the given string ends with one of the given terms.
*
* @since ostermillerutils 1.02.25
*/
public static boolean endsWithAny(String s, String[] terms){
return getEndsWithAnyPattern(terms).matcher(s).matches();
}
/**
* Tests to see if the given string contains any of the given terms.
* <p>
* Case is ignored when matching using Unicode case rules.
* <p>
* This implementation is more efficient than the brute force approach
* of testing the string against each of the terms. It instead compiles
* a single regular expression that can test all the terms at once, and
* uses that expression against the string.
* <p>
* This is a convenience method. If multiple strings are tested against
* the same set of terms, it is more efficient not to compile the regular
* expression multiple times.
* @see #getContainsAnyIgnoreCasePattern(String[])
*
* @param s String that may contain any of the given terms.
* @param terms list of substrings that may be contained in the given string.
* @return true iff one of the terms is a substring of the given string.
*
* @since ostermillerutils 1.02.25
*/
public static boolean containsAnyIgnoreCase(String s, String[] terms){
return getContainsAnyIgnoreCasePattern(terms).matcher(s).matches();
}
/**
* Tests to see if the given string equals any of the given terms.
* <p>
* Case is ignored when matching using Unicode case rules.
* <p>
* This implementation is more efficient than the brute force approach
* of testing the string against each of the terms. It instead compiles
* a single regular expression that can test all the terms at once, and
* uses that expression against the string.
* <p>
* This is a convenience method. If multiple strings are tested against
* the same set of terms, it is more efficient not to compile the regular
* expression multiple times.
* @see #getEqualsAnyIgnoreCasePattern(String[])
*
* @param s String that may equal any of the given terms.
* @param terms list of strings that may equal the given string.
* @return true iff one of the terms is equal to the given string.
*
* @since ostermillerutils 1.02.25
*/
public static boolean equalsAnyIgnoreCase(String s, String[] terms){
return getEqualsAnyIgnoreCasePattern(terms).matcher(s).matches();
}
/**
* Tests to see if the given string starts with any of the given terms.
* <p>
* Case is ignored when matching using Unicode case rules.
* <p>
* This implementation is more efficient than the brute force approach
* of testing the string against each of the terms. It instead compiles
* a single regular expression that can test all the terms at once, and
* uses that expression against the string.
* <p>
* This is a convenience method. If multiple strings are tested against
* the same set of terms, it is more efficient not to compile the regular
* expression multiple times.
* @see #getStartsWithAnyIgnoreCasePattern(String[])
*
* @param s String that may start with any of the given terms.
* @param terms list of strings that may start with the given string.
* @return true iff the given string starts with one of the given terms.
*
* @since ostermillerutils 1.02.25
*/
public static boolean startsWithAnyIgnoreCase(String s, String[] terms){
return getStartsWithAnyIgnoreCasePattern(terms).matcher(s).matches();
}
/**
* Tests to see if the given string ends with any of the given terms.
* <p>
* Case is ignored when matching using Unicode case rules.
* <p>
* This implementation is more efficient than the brute force approach
* of testing the string against each of the terms. It instead compiles
* a single regular expression that can test all the terms at once, and
* uses that expression against the string.
* <p>
* This is a convenience method. If multiple strings are tested against
* the same set of terms, it is more efficient not to compile the regular
* expression multiple times.
* @see #getEndsWithAnyIgnoreCasePattern(String[])
*
* @param s String that may end with any of the given terms.
* @param terms list of strings that may end with the given string.
* @return true iff the given string ends with one of the given terms.
*
* @since ostermillerutils 1.02.25
*/
public static boolean endsWithAnyIgnoreCase(String s, String[] terms){
return getEndsWithAnyIgnoreCasePattern(terms).matcher(s).matches();
}
}
Utility inserts a space before every caps in a string
public class Main{
public static String insertSpace( String str )
{
String chr;
StringBuffer buffer = new StringBuffer();
for( int i = 0; i < str.length(); i++ ){
chr = String.valueOf( str.charAt( i ));
if(( i > 0 ) && ( chr.matches( "[A-Z]")))
buffer.append( " ");
buffer.append( chr );
}
return buffer.toString();
}
}
Word Wrap
import java.text.BreakIterator;
import java.util.Locale;
/**
* $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.
*/
/**
* Utility class to peform common String manipulation algorithms.
*/
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.
}
/**
* Reformats a string where lines that are longer than <tt>width</tt>
* are split apart at the earliest wordbreak or at maxLength, whichever is
* sooner. If the width specified is less than 5 or greater than the input
* Strings length the string will be returned as is.
* <p/>
* Please note that this method can be lossy - trailing spaces on wrapped
* lines may be trimmed.
*
* @param input the String to reformat.
* @param width the maximum length of any one line.
* @return a new String with reformatted as needed.
*/
public static String wordWrap(String input, int width, Locale locale) {
// protect ourselves
if (input == null) {
return "";
}
else if (width < 5) {
return input;
}
else if (width >= input.length()) {
return input;
}
StringBuilder buf = new StringBuilder(input);
boolean endOfLine = false;
int lineStart = 0;
for (int i = 0; i < buf.length(); i++) {
if (buf.charAt(i) == "\n") {
lineStart = i + 1;
endOfLine = true;
}
// handle splitting at width character
if (i > lineStart + width - 1) {
if (!endOfLine) {
int limit = i - lineStart - 1;
BreakIterator breaks = BreakIterator.getLineInstance(locale);
breaks.setText(buf.substring(lineStart, i));
int end = breaks.last();
// if the last character in the search string isn"t a space,
// we can"t split on it (looks bad). Search for a previous
// break character
if (end == limit + 1) {
if (!Character.isWhitespace(buf.charAt(lineStart + end))) {
end = breaks.preceding(end - 1);
}
}
// if the last character is a space, replace it with a \n
if (end != BreakIterator.DONE && end == limit + 1) {
buf.replace(lineStart + end, lineStart + end + 1, "\n");
lineStart = lineStart + end;
}
// otherwise, just insert a \n
else if (end != BreakIterator.DONE && end != 0) {
buf.insert(lineStart + end, "\n");
lineStart = lineStart + end + 1;
}
else {
buf.insert(i, "\n");
lineStart = i + 1;
}
}
else {
buf.insert(i, "\n");
lineStart = i + 1;
endOfLine = false;
}
}
}
return buf.toString();
}
}