All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.yy.androidlib.util.apache.StringUtils Maven / Gradle / Ivy

There is a newer version: 1.0.5
Show newest version
/*
 * 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.
 */
package com.yy.androidlib.util.apache;

/**
 * 

Operations on {@link java.lang.String} that are * null safe.

*

*

    *
  • IsEmpty/IsBlank * - checks if a String contains text
  • *
  • Trim/Strip * - removes leading and trailing whitespace
  • *
  • Equals * - compares two strings null-safe
  • *
  • IndexOf/LastIndexOf/Contains * - null-safe index-of checks *
  • IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut * - index-of any of a set of Strings
  • *
  • ContainsOnly/ContainsNone * - does String contains only/none of these characters
  • *
  • Substring/Left/Right/Mid * - null-safe substring extractions
  • *
  • SubstringBefore/SubstringAfter/SubstringBetween * - substring extraction relative to other strings
  • *
  • Split/Join * - splits a String into an array of substrings and vice versa
  • *
  • Remove/Delete * - removes part of a String
  • *
  • Replace/Overlay * - Searches a String and replaces one String with another
  • *
  • Chomp/Chop * - removes the last part of a String
  • *
  • LeftPad/RightPad/Center/Repeat * - pads a String
  • *
  • UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize * - changes the case of a String
  • *
  • CountMatches * - counts the number of occurrences of one String in another
  • *
  • IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable * - checks the characters in a String
  • *
  • DefaultString * - protects against a null input String
  • *
  • Reverse/ReverseDelimited * - reverses a String
  • *
  • Abbreviate * - abbreviates a string using ellipsis
  • *
  • Difference * - compares two Strings and reports on their differences
  • *
  • LevensteinDistance * - the number of changes needed to change one String into another
  • *
*

*

The StringUtils class defines certain words related to * String handling.

*

*

    *
  • null - null
  • *
  • empty - a zero-length string ("")
  • *
  • space - the space character (' ', char 32)
  • *
  • whitespace - the characters defined by {@link Character#isWhitespace(char)}
  • *
  • trim - the characters <= 32 as in {@link String#trim()}
  • *
*

*

StringUtils handles null input Strings quietly. * That is to say that a null input will return null. * Where a boolean or int is being returned * details vary by method.

*

*

A side effect of the null handling is that a * NullPointerException should be considered a bug in * StringUtils (except for deprecated methods).

*

*

Methods in this class give sample code to explain their operation. * The symbol * is used to indicate any input including null.

* * @author Apache Jakarta Turbine * @author Jon S. Stevens * @author Daniel Rall * @author Greg Coladonato * @author Ed Korthof * @author Rand McNeely * @author Stephen Colebourne * @author Fredrik Westermarck * @author Holger Krauth * @author Alexander Day Chaffee * @author Henning P. Schmiedehausen * @author Arun Mammen Thomas * @author Gary Gregory * @author Phil Steitz * @author Al Chou * @author Michael Davey * @author Reuben Sivan * @author Chris Hyzer * @version $Id: StringUtils.java 492377 2007-01-04 01:20:30Z scolebourne $ * @see java.lang.String * @since 1.0 */ public class StringUtils { // Performance testing notes (JDK 1.4, Jul03, scolebourne) // Whitespace: // Character.isWhitespace() is faster than WHITESPACE.indexOf() // where WHITESPACE is a string of all whitespace characters // // Character access: // String.charAt(n) versus toCharArray(), then array[n] // String.charAt(n) is about 15% worse for a 10K string // They are about equal for a length 50 string // String.charAt(n) is about 4 times better for a length 3 string // String.charAt(n) is best bet overall // // Append: // String.concat about twice as fast as StringBuffer.append // (not sure who tested this) /** * The empty String "". * * @since 2.0 */ public static final String EMPTY = ""; /** * Represents a failed index search. * * @since 2.1 */ public static final int INDEX_NOT_FOUND = -1; /** *

The maximum size to which the padding constant(s) can expand.

*/ private static final int PAD_LIMIT = 8192; /** *

StringUtils instances should NOT be constructed in * standard programming. Instead, the class should be used as * StringUtils.trim(" foo ");.

*

*

This constructor is public to permit tools that require a JavaBean * instance to operate.

*/ public StringUtils() { super(); } // Empty checks //----------------------------------------------------------------------- /** *

Checks if a String is empty ("") or null.

*

*

     * StringUtils.isEmpty(null)      = true
     * StringUtils.isEmpty("")        = true
     * StringUtils.isEmpty(" ")       = false
     * StringUtils.isEmpty("bob")     = false
     * StringUtils.isEmpty("  bob  ") = false
     * 
*

*

NOTE: This method changed in Lang version 2.0. * It no longer trims the String. * That functionality is available in isBlank().

* * @param str the String to check, may be null * @return true if the String is empty or null */ public static boolean isEmpty(String str) { return str == null || str.length() == 0; } /** *

Checks if a String is not empty ("") and not null.

*

*

     * StringUtils.isNotEmpty(null)      = false
     * StringUtils.isNotEmpty("")        = false
     * StringUtils.isNotEmpty(" ")       = true
     * StringUtils.isNotEmpty("bob")     = true
     * StringUtils.isNotEmpty("  bob  ") = true
     * 
* * @param str the String to check, may be null * @return true if the String is not empty and not null */ public static boolean isNotEmpty(String str) { return !StringUtils.isEmpty(str); } /** *

Checks if a String is whitespace, empty ("") or null.

*

*

     * StringUtils.isBlank(null)      = true
     * StringUtils.isBlank("")        = true
     * StringUtils.isBlank(" ")       = true
     * StringUtils.isBlank("bob")     = false
     * StringUtils.isBlank("  bob  ") = false
     * 
* * @param str the String to check, may be null * @return true if the String is null, empty or whitespace * @since 2.0 */ public static boolean isBlank(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if (!(Character.isWhitespace(str.charAt(i)))) { return false; } } return true; } /** *

Checks if a String is not empty (""), not null and not whitespace only.

*

*

     * StringUtils.isNotBlank(null)      = false
     * StringUtils.isNotBlank("")        = false
     * StringUtils.isNotBlank(" ")       = false
     * StringUtils.isNotBlank("bob")     = true
     * StringUtils.isNotBlank("  bob  ") = true
     * 
* * @param str the String to check, may be null * @return true if the String is * not empty and not null and not whitespace * @since 2.0 */ public static boolean isNotBlank(String str) { return !StringUtils.isBlank(str); } // Trim //----------------------------------------------------------------------- /** *

Removes control characters (char <= 32) from both * ends of this String, handling null by returning * an empty String ("").

*

*

     * StringUtils.clean(null)          = ""
     * StringUtils.clean("")            = ""
     * StringUtils.clean("abc")         = "abc"
     * StringUtils.clean("    abc    ") = "abc"
     * StringUtils.clean("     ")       = ""
     * 
* * @param str the String to clean, may be null * @return the trimmed text, never null * @see java.lang.String#trim() * @deprecated Use the clearer named {@link #trimToEmpty(String)}. * Method will be removed in Commons Lang 3.0. */ public static String clean(String str) { return str == null ? EMPTY : str.trim(); } /** *

Removes control characters (char <= 32) from both * ends of this String, handling null by returning * null.

*

*

The String is trimmed using {@link String#trim()}. * Trim removes start and end characters <= 32. * To strip whitespace use {@link #strip(String)}.

*

*

To trim your choice of characters, use the * {@link #strip(String, String)} methods.

*

*

     * StringUtils.trim(null)          = null
     * StringUtils.trim("")            = ""
     * StringUtils.trim("     ")       = ""
     * StringUtils.trim("abc")         = "abc"
     * StringUtils.trim("    abc    ") = "abc"
     * 
* * @param str the String to be trimmed, may be null * @return the trimmed string, null if null String input */ public static String trim(String str) { return str == null ? null : str.trim(); } /** *

Removes control characters (char <= 32) from both * ends of this String returning null if the String is * empty ("") after the trim or if it is null. *

*

The String is trimmed using {@link String#trim()}. * Trim removes start and end characters <= 32. * To strip whitespace use {@link #stripToNull(String)}.

*

*

     * StringUtils.trimToNull(null)          = null
     * StringUtils.trimToNull("")            = null
     * StringUtils.trimToNull("     ")       = null
     * StringUtils.trimToNull("abc")         = "abc"
     * StringUtils.trimToNull("    abc    ") = "abc"
     * 
* * @param str the String to be trimmed, may be null * @return the trimmed String, * null if only chars <= 32, empty or null String input * @since 2.0 */ public static String trimToNull(String str) { String ts = trim(str); return isEmpty(ts) ? null : ts; } /** *

Removes control characters (char <= 32) from both * ends of this String returning an empty String ("") if the String * is empty ("") after the trim or if it is null. *

*

The String is trimmed using {@link String#trim()}. * Trim removes start and end characters <= 32. * To strip whitespace use {@link #stripToEmpty(String)}.

*

*

     * StringUtils.trimToEmpty(null)          = ""
     * StringUtils.trimToEmpty("")            = ""
     * StringUtils.trimToEmpty("     ")       = ""
     * StringUtils.trimToEmpty("abc")         = "abc"
     * StringUtils.trimToEmpty("    abc    ") = "abc"
     * 
* * @param str the String to be trimmed, may be null * @return the trimmed String, or an empty String if null input * @since 2.0 */ public static String trimToEmpty(String str) { return str == null ? EMPTY : str.trim(); } // Stripping //----------------------------------------------------------------------- /** *

Strips whitespace from the start and end of a String.

*

*

This is similar to {@link #trim(String)} but removes whitespace. * Whitespace is defined by {@link Character#isWhitespace(char)}.

*

*

A null input String returns null.

*

*

     * StringUtils.strip(null)     = null
     * StringUtils.strip("")       = ""
     * StringUtils.strip("   ")    = ""
     * StringUtils.strip("abc")    = "abc"
     * StringUtils.strip("  abc")  = "abc"
     * StringUtils.strip("abc  ")  = "abc"
     * StringUtils.strip(" abc ")  = "abc"
     * StringUtils.strip(" ab c ") = "ab c"
     * 
* * @param str the String to remove whitespace from, may be null * @return the stripped String, null if null String input */ public static String strip(String str) { return strip(str, null); } /** *

Strips whitespace from the start and end of a String returning * null if the String is empty ("") after the strip.

*

*

This is similar to {@link #trimToNull(String)} but removes whitespace. * Whitespace is defined by {@link Character#isWhitespace(char)}.

*

*

     * StringUtils.stripToNull(null)     = null
     * StringUtils.stripToNull("")       = null
     * StringUtils.stripToNull("   ")    = null
     * StringUtils.stripToNull("abc")    = "abc"
     * StringUtils.stripToNull("  abc")  = "abc"
     * StringUtils.stripToNull("abc  ")  = "abc"
     * StringUtils.stripToNull(" abc ")  = "abc"
     * StringUtils.stripToNull(" ab c ") = "ab c"
     * 
* * @param str the String to be stripped, may be null * @return the stripped String, * null if whitespace, empty or null String input * @since 2.0 */ public static String stripToNull(String str) { if (str == null) { return null; } str = strip(str, null); return str.length() == 0 ? null : str; } /** *

Strips whitespace from the start and end of a String returning * an empty String if null input.

*

*

This is similar to {@link #trimToEmpty(String)} but removes whitespace. * Whitespace is defined by {@link Character#isWhitespace(char)}.

*

*

     * StringUtils.stripToEmpty(null)     = ""
     * StringUtils.stripToEmpty("")       = ""
     * StringUtils.stripToEmpty("   ")    = ""
     * StringUtils.stripToEmpty("abc")    = "abc"
     * StringUtils.stripToEmpty("  abc")  = "abc"
     * StringUtils.stripToEmpty("abc  ")  = "abc"
     * StringUtils.stripToEmpty(" abc ")  = "abc"
     * StringUtils.stripToEmpty(" ab c ") = "ab c"
     * 
* * @param str the String to be stripped, may be null * @return the trimmed String, or an empty String if null input * @since 2.0 */ public static String stripToEmpty(String str) { return str == null ? EMPTY : strip(str, null); } /** *

Strips any of a set of characters from the start and end of a String. * This is similar to {@link String#trim()} but allows the characters * to be stripped to be controlled.

*

*

A null input String returns null. * An empty string ("") input returns the empty string.

*

*

If the stripChars String is null, whitespace is * stripped as defined by {@link Character#isWhitespace(char)}. * Alternatively use {@link #strip(String)}.

*

*

     * StringUtils.strip(null, *)          = null
     * StringUtils.strip("", *)            = ""
     * StringUtils.strip("abc", null)      = "abc"
     * StringUtils.strip("  abc", null)    = "abc"
     * StringUtils.strip("abc  ", null)    = "abc"
     * StringUtils.strip(" abc ", null)    = "abc"
     * StringUtils.strip("  abcyx", "xyz") = "  abc"
     * 
* * @param str the String to remove characters from, may be null * @param stripChars the characters to remove, null treated as whitespace * @return the stripped String, null if null String input */ public static String strip(String str, String stripChars) { if (isEmpty(str)) { return str; } str = stripStart(str, stripChars); return stripEnd(str, stripChars); } /** *

Strips any of a set of characters from the start of a String.

*

*

A null input String returns null. * An empty string ("") input returns the empty string.

*

*

If the stripChars String is null, whitespace is * stripped as defined by {@link Character#isWhitespace(char)}.

*

*

     * StringUtils.stripStart(null, *)          = null
     * StringUtils.stripStart("", *)            = ""
     * StringUtils.stripStart("abc", "")        = "abc"
     * StringUtils.stripStart("abc", null)      = "abc"
     * StringUtils.stripStart("  abc", null)    = "abc"
     * StringUtils.stripStart("abc  ", null)    = "abc  "
     * StringUtils.stripStart(" abc ", null)    = "abc "
     * StringUtils.stripStart("yxabc  ", "xyz") = "abc  "
     * 
* * @param str the String to remove characters from, may be null * @param stripChars the characters to remove, null treated as whitespace * @return the stripped String, null if null String input */ public static String stripStart(String str, String stripChars) { int strLen; if (str == null || (strLen = str.length()) == 0) { return str; } int start = 0; if (stripChars == null) { while ((start != strLen) && Character.isWhitespace(str.charAt(start))) { start++; } } else if (stripChars.length() == 0) { return str; } else { while ((start != strLen) && (stripChars.indexOf(str.charAt(start)) != -1)) { start++; } } return str.substring(start); } /** *

Strips any of a set of characters from the end of a String.

*

*

A null input String returns null. * An empty string ("") input returns the empty string.

*

*

If the stripChars String is null, whitespace is * stripped as defined by {@link Character#isWhitespace(char)}.

*

*

     * StringUtils.stripEnd(null, *)          = null
     * StringUtils.stripEnd("", *)            = ""
     * StringUtils.stripEnd("abc", "")        = "abc"
     * StringUtils.stripEnd("abc", null)      = "abc"
     * StringUtils.stripEnd("  abc", null)    = "  abc"
     * StringUtils.stripEnd("abc  ", null)    = "abc"
     * StringUtils.stripEnd(" abc ", null)    = " abc"
     * StringUtils.stripEnd("  abcyx", "xyz") = "  abc"
     * 
* * @param str the String to remove characters from, may be null * @param stripChars the characters to remove, null treated as whitespace * @return the stripped String, null if null String input */ public static String stripEnd(String str, String stripChars) { int end; if (str == null || (end = str.length()) == 0) { return str; } if (stripChars == null) { while ((end != 0) && Character.isWhitespace(str.charAt(end - 1))) { end--; } } else if (stripChars.length() == 0) { return str; } else { while ((end != 0) && (stripChars.indexOf(str.charAt(end - 1)) != -1)) { end--; } } return str.substring(0, end); } // StripAll //----------------------------------------------------------------------- /** *

Strips whitespace from the start and end of every String in an array. * Whitespace is defined by {@link Character#isWhitespace(char)}.

*

*

A new array is returned each time, except for length zero. * A null array will return null. * An empty array will return itself. * A null array entry will be ignored.

*

*

     * StringUtils.stripAll(null)             = null
     * StringUtils.stripAll([])               = []
     * StringUtils.stripAll(["abc", "  abc"]) = ["abc", "abc"]
     * StringUtils.stripAll(["abc  ", null])  = ["abc", null]
     * 
* * @param strs the array to remove whitespace from, may be null * @return the stripped Strings, null if null array input */ public static String[] stripAll(String[] strs) { return stripAll(strs, null); } /** *

Strips any of a set of characters from the start and end of every * String in an array.

* Whitespace is defined by {@link Character#isWhitespace(char)}.

*

*

A new array is returned each time, except for length zero. * A null array will return null. * An empty array will return itself. * A null array entry will be ignored. * A null stripChars will strip whitespace as defined by * {@link Character#isWhitespace(char)}.

*

*

     * StringUtils.stripAll(null, *)                = null
     * StringUtils.stripAll([], *)                  = []
     * StringUtils.stripAll(["abc", "  abc"], null) = ["abc", "abc"]
     * StringUtils.stripAll(["abc  ", null], null)  = ["abc", null]
     * StringUtils.stripAll(["abc  ", null], "yz")  = ["abc  ", null]
     * StringUtils.stripAll(["yabcz", null], "yz")  = ["abc", null]
     * 
* * @param strs the array to remove characters from, may be null * @param stripChars the characters to remove, null treated as whitespace * @return the stripped Strings, null if null array input */ public static String[] stripAll(String[] strs, String stripChars) { int strsLen; if (strs == null || (strsLen = strs.length) == 0) { return strs; } String[] newArr = new String[strsLen]; for (int i = 0; i < strsLen; i++) { newArr[i] = strip(strs[i], stripChars); } return newArr; } // Equals //----------------------------------------------------------------------- /** *

Compares two Strings, returning true if they are equal.

*

*

nulls are handled without exceptions. Two null * references are considered to be equal. The comparison is case sensitive.

*

*

     * StringUtils.equals(null, null)   = true
     * StringUtils.equals(null, "abc")  = false
     * StringUtils.equals("abc", null)  = false
     * StringUtils.equals("abc", "abc") = true
     * StringUtils.equals("abc", "ABC") = false
     * 
* * @param str1 the first String, may be null * @param str2 the second String, may be null * @return true if the Strings are equal, case sensitive, or * both null * @see java.lang.String#equals(Object) */ public static boolean equals(String str1, String str2) { return str1 == null ? str2 == null : str1.equals(str2); } /** *

Compares two Strings, returning true if they are equal ignoring * the case.

*

*

nulls are handled without exceptions. Two null * references are considered equal. Comparison is case insensitive.

*

*

     * StringUtils.equalsIgnoreCase(null, null)   = true
     * StringUtils.equalsIgnoreCase(null, "abc")  = false
     * StringUtils.equalsIgnoreCase("abc", null)  = false
     * StringUtils.equalsIgnoreCase("abc", "abc") = true
     * StringUtils.equalsIgnoreCase("abc", "ABC") = true
     * 
* * @param str1 the first String, may be null * @param str2 the second String, may be null * @return true if the Strings are equal, case insensitive, or * both null * @see java.lang.String#equalsIgnoreCase(String) */ public static boolean equalsIgnoreCase(String str1, String str2) { return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2); } // IndexOf //----------------------------------------------------------------------- /** *

Finds the first index within a String, handling null. * This method uses {@link String#indexOf(int)}.

*

*

A null or empty ("") String will return -1.

*

*

     * StringUtils.indexOf(null, *)         = -1
     * StringUtils.indexOf("", *)           = -1
     * StringUtils.indexOf("aabaabaa", 'a') = 0
     * StringUtils.indexOf("aabaabaa", 'b') = 2
     * 
* * @param str the String to check, may be null * @param searchChar the character to find * @return the first index of the search character, * -1 if no match or null string input * @since 2.0 */ public static int indexOf(String str, char searchChar) { if (isEmpty(str)) { return -1; } return str.indexOf(searchChar); } /** *

Finds the first index within a String from a start position, * handling null. * This method uses {@link String#indexOf(int, int)}.

*

*

A null or empty ("") String will return -1. * A negative start position is treated as zero. * A start position greater than the string length returns -1.

*

*

     * StringUtils.indexOf(null, *, *)          = -1
     * StringUtils.indexOf("", *, *)            = -1
     * StringUtils.indexOf("aabaabaa", 'b', 0)  = 2
     * StringUtils.indexOf("aabaabaa", 'b', 3)  = 5
     * StringUtils.indexOf("aabaabaa", 'b', 9)  = -1
     * StringUtils.indexOf("aabaabaa", 'b', -1) = 2
     * 
* * @param str the String to check, may be null * @param searchChar the character to find * @param startPos the start position, negative treated as zero * @return the first index of the search character, * -1 if no match or null string input * @since 2.0 */ public static int indexOf(String str, char searchChar, int startPos) { if (isEmpty(str)) { return -1; } return str.indexOf(searchChar, startPos); } /** *

Finds the first index within a String, handling null. * This method uses {@link String#indexOf(String)}.

*

*

A null String will return -1.

*

*

     * StringUtils.indexOf(null, *)          = -1
     * StringUtils.indexOf(*, null)          = -1
     * StringUtils.indexOf("", "")           = 0
     * StringUtils.indexOf("aabaabaa", "a")  = 0
     * StringUtils.indexOf("aabaabaa", "b")  = 2
     * StringUtils.indexOf("aabaabaa", "ab") = 1
     * StringUtils.indexOf("aabaabaa", "")   = 0
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @return the first index of the search String, * -1 if no match or null string input * @since 2.0 */ public static int indexOf(String str, String searchStr) { if (str == null || searchStr == null) { return -1; } return str.indexOf(searchStr); } /** *

Finds the n-th index within a String, handling null. * This method uses {@link String#indexOf(String)}.

*

*

A null String will return -1.

*

*

     * StringUtils.ordinalIndexOf(null, *, *)          = -1
     * StringUtils.ordinalIndexOf(*, null, *)          = -1
     * StringUtils.ordinalIndexOf("", "", *)           = 0
     * StringUtils.ordinalIndexOf("aabaabaa", "a", 1)  = 0
     * StringUtils.ordinalIndexOf("aabaabaa", "a", 2)  = 1
     * StringUtils.ordinalIndexOf("aabaabaa", "b", 1)  = 2
     * StringUtils.ordinalIndexOf("aabaabaa", "b", 2)  = 5
     * StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1
     * StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4
     * StringUtils.ordinalIndexOf("aabaabaa", "", 1)   = 0
     * StringUtils.ordinalIndexOf("aabaabaa", "", 2)   = 0
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @param ordinal the n-th searchStr to find * @return the n-th index of the search String, * -1 (INDEX_NOT_FOUND) if no match or null string input * @since 2.1 */ public static int ordinalIndexOf(String str, String searchStr, int ordinal) { if (str == null || searchStr == null || ordinal <= 0) { return INDEX_NOT_FOUND; } if (searchStr.length() == 0) { return 0; } int found = 0; int index = INDEX_NOT_FOUND; do { index = str.indexOf(searchStr, index + 1); if (index < 0) { return index; } found++; } while (found < ordinal); return index; } /** *

Finds the first index within a String, handling null. * This method uses {@link String#indexOf(String, int)}.

*

*

A null String will return -1. * A negative start position is treated as zero. * An empty ("") search String always matches. * A start position greater than the string length only matches * an empty search String.

*

*

     * StringUtils.indexOf(null, *, *)          = -1
     * StringUtils.indexOf(*, null, *)          = -1
     * StringUtils.indexOf("", "", 0)           = 0
     * StringUtils.indexOf("aabaabaa", "a", 0)  = 0
     * StringUtils.indexOf("aabaabaa", "b", 0)  = 2
     * StringUtils.indexOf("aabaabaa", "ab", 0) = 1
     * StringUtils.indexOf("aabaabaa", "b", 3)  = 5
     * StringUtils.indexOf("aabaabaa", "b", 9)  = -1
     * StringUtils.indexOf("aabaabaa", "b", -1) = 2
     * StringUtils.indexOf("aabaabaa", "", 2)   = 2
     * StringUtils.indexOf("abc", "", 9)        = 3
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @param startPos the start position, negative treated as zero * @return the first index of the search String, * -1 if no match or null string input * @since 2.0 */ public static int indexOf(String str, String searchStr, int startPos) { if (str == null || searchStr == null) { return -1; } // JDK1.2/JDK1.3 have a bug, when startPos > str.length for "", hence if (searchStr.length() == 0 && startPos >= str.length()) { return str.length(); } return str.indexOf(searchStr, startPos); } // LastIndexOf //----------------------------------------------------------------------- /** *

Finds the last index within a String, handling null. * This method uses {@link String#lastIndexOf(int)}.

*

*

A null or empty ("") String will return -1.

*

*

     * StringUtils.lastIndexOf(null, *)         = -1
     * StringUtils.lastIndexOf("", *)           = -1
     * StringUtils.lastIndexOf("aabaabaa", 'a') = 7
     * StringUtils.lastIndexOf("aabaabaa", 'b') = 5
     * 
* * @param str the String to check, may be null * @param searchChar the character to find * @return the last index of the search character, * -1 if no match or null string input * @since 2.0 */ public static int lastIndexOf(String str, char searchChar) { if (isEmpty(str)) { return -1; } return str.lastIndexOf(searchChar); } /** *

Finds the last index within a String from a start position, * handling null. * This method uses {@link String#lastIndexOf(int, int)}.

*

*

A null or empty ("") String will return -1. * A negative start position returns -1. * A start position greater than the string length searches the whole string.

*

*

     * StringUtils.lastIndexOf(null, *, *)          = -1
     * StringUtils.lastIndexOf("", *,  *)           = -1
     * StringUtils.lastIndexOf("aabaabaa", 'b', 8)  = 5
     * StringUtils.lastIndexOf("aabaabaa", 'b', 4)  = 2
     * StringUtils.lastIndexOf("aabaabaa", 'b', 0)  = -1
     * StringUtils.lastIndexOf("aabaabaa", 'b', 9)  = 5
     * StringUtils.lastIndexOf("aabaabaa", 'b', -1) = -1
     * StringUtils.lastIndexOf("aabaabaa", 'a', 0)  = 0
     * 
* * @param str the String to check, may be null * @param searchChar the character to find * @param startPos the start position * @return the last index of the search character, * -1 if no match or null string input * @since 2.0 */ public static int lastIndexOf(String str, char searchChar, int startPos) { if (isEmpty(str)) { return -1; } return str.lastIndexOf(searchChar, startPos); } /** *

Finds the last index within a String, handling null. * This method uses {@link String#lastIndexOf(String)}.

*

*

A null String will return -1.

*

*

     * StringUtils.lastIndexOf(null, *)          = -1
     * StringUtils.lastIndexOf(*, null)          = -1
     * StringUtils.lastIndexOf("", "")           = 0
     * StringUtils.lastIndexOf("aabaabaa", "a")  = 0
     * StringUtils.lastIndexOf("aabaabaa", "b")  = 2
     * StringUtils.lastIndexOf("aabaabaa", "ab") = 1
     * StringUtils.lastIndexOf("aabaabaa", "")   = 8
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @return the last index of the search String, * -1 if no match or null string input * @since 2.0 */ public static int lastIndexOf(String str, String searchStr) { if (str == null || searchStr == null) { return -1; } return str.lastIndexOf(searchStr); } /** *

Finds the first index within a String, handling null. * This method uses {@link String#lastIndexOf(String, int)}.

*

*

A null String will return -1. * A negative start position returns -1. * An empty ("") search String always matches unless the start position is negative. * A start position greater than the string length searches the whole string.

*

*

     * StringUtils.lastIndexOf(null, *, *)          = -1
     * StringUtils.lastIndexOf(*, null, *)          = -1
     * StringUtils.lastIndexOf("aabaabaa", "a", 8)  = 7
     * StringUtils.lastIndexOf("aabaabaa", "b", 8)  = 5
     * StringUtils.lastIndexOf("aabaabaa", "ab", 8) = 4
     * StringUtils.lastIndexOf("aabaabaa", "b", 9)  = 5
     * StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1
     * StringUtils.lastIndexOf("aabaabaa", "a", 0)  = 0
     * StringUtils.lastIndexOf("aabaabaa", "b", 0)  = -1
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @param startPos the start position, negative treated as zero * @return the first index of the search String, * -1 if no match or null string input * @since 2.0 */ public static int lastIndexOf(String str, String searchStr, int startPos) { if (str == null || searchStr == null) { return -1; } return str.lastIndexOf(searchStr, startPos); } // Contains //----------------------------------------------------------------------- /** *

Checks if String contains a search character, handling null. * This method uses {@link String#indexOf(int)}.

*

*

A null or empty ("") String will return false.

*

*

     * StringUtils.contains(null, *)    = false
     * StringUtils.contains("", *)      = false
     * StringUtils.contains("abc", 'a') = true
     * StringUtils.contains("abc", 'z') = false
     * 
* * @param str the String to check, may be null * @param searchChar the character to find * @return true if the String contains the search character, * false if not or null string input * @since 2.0 */ public static boolean contains(String str, char searchChar) { if (isEmpty(str)) { return false; } return str.indexOf(searchChar) >= 0; } /** *

Checks if String contains a search String, handling null. * This method uses {@link String#indexOf(String)}.

*

*

A null String will return false.

*

*

     * StringUtils.contains(null, *)     = false
     * StringUtils.contains(*, null)     = false
     * StringUtils.contains("", "")      = true
     * StringUtils.contains("abc", "")   = true
     * StringUtils.contains("abc", "a")  = true
     * StringUtils.contains("abc", "z")  = false
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @return true if the String contains the search String, * false if not or null string input * @since 2.0 */ public static boolean contains(String str, String searchStr) { if (str == null || searchStr == null) { return false; } return str.indexOf(searchStr) >= 0; } /** *

Checks if String contains a search String irrespective of case, * handling null. This method uses * {@link #contains(String, String)}.

*

*

A null String will return false.

*

*

     * StringUtils.contains(null, *) = false
     * StringUtils.contains(*, null) = false
     * StringUtils.contains("", "") = true
     * StringUtils.contains("abc", "") = true
     * StringUtils.contains("abc", "a") = true
     * StringUtils.contains("abc", "z") = false
     * StringUtils.contains("abc", "A") = true
     * StringUtils.contains("abc", "Z") = false
     * 
* * @param str the String to check, may be null * @param searchStr the String to find, may be null * @return true if the String contains the search String irrespective of * case or false if not or null string input */ public static boolean containsIgnoreCase(String str, String searchStr) { if (str == null || searchStr == null) { return false; } return contains(str.toUpperCase(), searchStr.toUpperCase()); } /** *

Search a String to find the first index of any * character not in the given set of characters.

*

*

A null String will return -1. * A null search string will return -1.

*

*

     * StringUtils.indexOfAnyBut(null, *)            = -1
     * StringUtils.indexOfAnyBut("", *)              = -1
     * StringUtils.indexOfAnyBut(*, null)            = -1
     * StringUtils.indexOfAnyBut(*, "")              = -1
     * StringUtils.indexOfAnyBut("zzabyycdxx", "za") = 3
     * StringUtils.indexOfAnyBut("zzabyycdxx", "")   = 0
     * StringUtils.indexOfAnyBut("aba","ab")         = -1
     * 
* * @param str the String to check, may be null * @param searchChars the chars to search for, may be null * @return the index of any of the chars, -1 if no match or null input * @since 2.0 */ public static int indexOfAnyBut(String str, String searchChars) { if (isEmpty(str) || isEmpty(searchChars)) { return -1; } for (int i = 0; i < str.length(); i++) { if (searchChars.indexOf(str.charAt(i)) < 0) { return i; } } return -1; } // ContainsNone //----------------------------------------------------------------------- /** *

Checks that the String does not contain certain characters.

*

*

A null String will return true. * A null invalid character array will return true. * An empty String ("") always returns true.

*

*

     * StringUtils.containsNone(null, *)       = true
     * StringUtils.containsNone(*, null)       = true
     * StringUtils.containsNone("", *)         = true
     * StringUtils.containsNone("ab", '')      = true
     * StringUtils.containsNone("abab", 'xyz') = true
     * StringUtils.containsNone("ab1", 'xyz')  = true
     * StringUtils.containsNone("abz", 'xyz')  = false
     * 
* * @param str the String to check, may be null * @param invalidChars an array of invalid chars, may be null * @return true if it contains none of the invalid chars, or is null * @since 2.0 */ public static boolean containsNone(String str, char[] invalidChars) { if (str == null || invalidChars == null) { return true; } int strSize = str.length(); int validSize = invalidChars.length; for (int i = 0; i < strSize; i++) { char ch = str.charAt(i); for (int j = 0; j < validSize; j++) { if (invalidChars[j] == ch) { return false; } } } return true; } /** *

Checks that the String does not contain certain characters.

*

*

A null String will return true. * A null invalid character array will return true. * An empty String ("") always returns true.

*

*

     * StringUtils.containsNone(null, *)       = true
     * StringUtils.containsNone(*, null)       = true
     * StringUtils.containsNone("", *)         = true
     * StringUtils.containsNone("ab", "")      = true
     * StringUtils.containsNone("abab", "xyz") = true
     * StringUtils.containsNone("ab1", "xyz")  = true
     * StringUtils.containsNone("abz", "xyz")  = false
     * 
* * @param str the String to check, may be null * @param invalidChars a String of invalid chars, may be null * @return true if it contains none of the invalid chars, or is null * @since 2.0 */ public static boolean containsNone(String str, String invalidChars) { if (str == null || invalidChars == null) { return true; } return containsNone(str, invalidChars.toCharArray()); } // SubStringAfter/SubStringBefore //----------------------------------------------------------------------- /** *

Gets the substring before the first occurrence of a separator. * The separator is not returned.

*

*

A null string input will return null. * An empty ("") string input will return the empty string. * A null separator will return the input string.

*

*

     * StringUtils.substringBefore(null, *)      = null
     * StringUtils.substringBefore("", *)        = ""
     * StringUtils.substringBefore("abc", "a")   = ""
     * StringUtils.substringBefore("abcba", "b") = "a"
     * StringUtils.substringBefore("abc", "c")   = "ab"
     * StringUtils.substringBefore("abc", "d")   = "abc"
     * StringUtils.substringBefore("abc", "")    = ""
     * StringUtils.substringBefore("abc", null)  = "abc"
     * 
* * @param str the String to get a substring from, may be null * @param separator the String to search for, may be null * @return the substring before the first occurrence of the separator, * null if null String input * @since 2.0 */ public static String substringBefore(String str, String separator) { if (isEmpty(str) || separator == null) { return str; } if (separator.length() == 0) { return EMPTY; } int pos = str.indexOf(separator); if (pos == -1) { return str; } return str.substring(0, pos); } /** *

Gets the substring after the first occurrence of a separator. * The separator is not returned.

*

*

A null string input will return null. * An empty ("") string input will return the empty string. * A null separator will return the empty string if the * input string is not null.

*

*

     * StringUtils.substringAfter(null, *)      = null
     * StringUtils.substringAfter("", *)        = ""
     * StringUtils.substringAfter(*, null)      = ""
     * StringUtils.substringAfter("abc", "a")   = "bc"
     * StringUtils.substringAfter("abcba", "b") = "cba"
     * StringUtils.substringAfter("abc", "c")   = ""
     * StringUtils.substringAfter("abc", "d")   = ""
     * StringUtils.substringAfter("abc", "")    = "abc"
     * 
* * @param str the String to get a substring from, may be null * @param separator the String to search for, may be null * @return the substring after the first occurrence of the separator, * null if null String input * @since 2.0 */ public static String substringAfter(String str, String separator) { if (isEmpty(str)) { return str; } if (separator == null) { return EMPTY; } int pos = str.indexOf(separator); if (pos == -1) { return EMPTY; } return str.substring(pos + separator.length()); } /** *

Gets the substring before the last occurrence of a separator. * The separator is not returned.

*

*

A null string input will return null. * An empty ("") string input will return the empty string. * An empty or null separator will return the input string.

*

*

     * StringUtils.substringBeforeLast(null, *)      = null
     * StringUtils.substringBeforeLast("", *)        = ""
     * StringUtils.substringBeforeLast("abcba", "b") = "abc"
     * StringUtils.substringBeforeLast("abc", "c")   = "ab"
     * StringUtils.substringBeforeLast("a", "a")     = ""
     * StringUtils.substringBeforeLast("a", "z")     = "a"
     * StringUtils.substringBeforeLast("a", null)    = "a"
     * StringUtils.substringBeforeLast("a", "")      = "a"
     * 
* * @param str the String to get a substring from, may be null * @param separator the String to search for, may be null * @return the substring before the last occurrence of the separator, * null if null String input * @since 2.0 */ public static String substringBeforeLast(String str, String separator) { if (isEmpty(str) || isEmpty(separator)) { return str; } int pos = str.lastIndexOf(separator); if (pos == -1) { return str; } return str.substring(0, pos); } /** *

Gets the substring after the last occurrence of a separator. * The separator is not returned.

*

*

A null string input will return null. * An empty ("") string input will return the empty string. * An empty or null separator will return the empty string if * the input string is not null.

*

*

     * StringUtils.substringAfterLast(null, *)      = null
     * StringUtils.substringAfterLast("", *)        = ""
     * StringUtils.substringAfterLast(*, "")        = ""
     * StringUtils.substringAfterLast(*, null)      = ""
     * StringUtils.substringAfterLast("abc", "a")   = "bc"
     * StringUtils.substringAfterLast("abcba", "b") = "a"
     * StringUtils.substringAfterLast("abc", "c")   = ""
     * StringUtils.substringAfterLast("a", "a")     = ""
     * StringUtils.substringAfterLast("a", "z")     = ""
     * 
* * @param str the String to get a substring from, may be null * @param separator the String to search for, may be null * @return the substring after the last occurrence of the separator, * null if null String input * @since 2.0 */ public static String substringAfterLast(String str, String separator) { if (isEmpty(str)) { return str; } if (isEmpty(separator)) { return EMPTY; } int pos = str.lastIndexOf(separator); if (pos == -1 || pos == (str.length() - separator.length())) { return EMPTY; } return str.substring(pos + separator.length()); } // Substring between //----------------------------------------------------------------------- /** *

Gets the String that is nested in between two instances of the * same String.

*

*

A null input String returns null. * A null tag returns null.

*

*

     * StringUtils.substringBetween(null, *)            = null
     * StringUtils.substringBetween("", "")             = ""
     * StringUtils.substringBetween("", "tag")          = null
     * StringUtils.substringBetween("tagabctag", null)  = null
     * StringUtils.substringBetween("tagabctag", "")    = ""
     * StringUtils.substringBetween("tagabctag", "tag") = "abc"
     * 
* * @param str the String containing the substring, may be null * @param tag the String before and after the substring, may be null * @return the substring, null if no match * @since 2.0 */ public static String substringBetween(String str, String tag) { return substringBetween(str, tag, tag); } /** *

Gets the String that is nested in between two Strings. * Only the first match is returned.

*

*

A null input String returns null. * A null open/close returns null (no match). * An empty ("") open and close returns an empty string.

*

*

     * StringUtils.substringBetween("wx[b]yz", "[", "]") = "b"
     * StringUtils.substringBetween(null, *, *)          = null
     * StringUtils.substringBetween(*, null, *)          = null
     * StringUtils.substringBetween(*, *, null)          = null
     * StringUtils.substringBetween("", "", "")          = ""
     * StringUtils.substringBetween("", "", "]")         = null
     * StringUtils.substringBetween("", "[", "]")        = null
     * StringUtils.substringBetween("yabcz", "", "")     = ""
     * StringUtils.substringBetween("yabcz", "y", "z")   = "abc"
     * StringUtils.substringBetween("yabczyabcz", "y", "z")   = "abc"
     * 
* * @param str the String containing the substring, may be null * @param open the String before the substring, may be null * @param close the String after the substring, may be null * @return the substring, null if no match * @since 2.0 */ public static String substringBetween(String str, String open, String close) { if (str == null || open == null || close == null) { return null; } int start = str.indexOf(open); if (start != -1) { int end = str.indexOf(close, start + open.length()); if (end != -1) { return str.substring(start + open.length(), end); } } return null; } // Joining //----------------------------------------------------------------------- /** *

Concatenates elements of an array into a single String. * Null objects or empty strings within the array are represented by * empty strings.

*

*

     * StringUtils.concatenate(null)            = null
     * StringUtils.concatenate([])              = ""
     * StringUtils.concatenate([null])          = ""
     * StringUtils.concatenate(["a", "b", "c"]) = "abc"
     * StringUtils.concatenate([null, "", "a"]) = "a"
     * 
* * @param array the array of values to concatenate, may be null * @return the concatenated String, null if null array input * @deprecated Use the better named {@link #join(Object[])} instead. * Method will be removed in Commons Lang 3.0. */ public static String concatenate(Object[] array) { return join(array, null); } /** *

Joins the elements of the provided array into a single String * containing the provided list of elements.

*

*

No separator is added to the joined String. * Null objects or empty strings within the array are represented by * empty strings.

*

*

     * StringUtils.join(null)            = null
     * StringUtils.join([])              = ""
     * StringUtils.join([null])          = ""
     * StringUtils.join(["a", "b", "c"]) = "abc"
     * StringUtils.join([null, "", "a"]) = "a"
     * 
* * @param array the array of values to join together, may be null * @return the joined String, null if null array input * @since 2.0 */ public static String join(Object[] array) { return join(array, null); } /** *

Joins the elements of the provided array into a single String * containing the provided list of elements.

*

*

No delimiter is added before or after the list. * Null objects or empty strings within the array are represented by * empty strings.

*

*

     * StringUtils.join(null, *)               = null
     * StringUtils.join([], *)                 = ""
     * StringUtils.join([null], *)             = ""
     * StringUtils.join(["a", "b", "c"], ';')  = "a;b;c"
     * StringUtils.join(["a", "b", "c"], null) = "abc"
     * StringUtils.join([null, "", "a"], ';')  = ";;a"
     * 
* * @param array the array of values to join together, may be null * @param separator the separator character to use * @return the joined String, null if null array input * @since 2.0 */ public static String join(Object[] array, char separator) { if (array == null) { return null; } return join(array, separator, 0, array.length); } /** *

Joins the elements of the provided array into a single String * containing the provided list of elements.

*

*

No delimiter is added before or after the list. * Null objects or empty strings within the array are represented by * empty strings.

*

*

     * StringUtils.join(null, *)               = null
     * StringUtils.join([], *)                 = ""
     * StringUtils.join([null], *)             = ""
     * StringUtils.join(["a", "b", "c"], ';')  = "a;b;c"
     * StringUtils.join(["a", "b", "c"], null) = "abc"
     * StringUtils.join([null, "", "a"], ';')  = ";;a"
     * 
* * @param array the array of values to join together, may be null * @param separator the separator character to use * @param startIndex the first index to start joining from. It is * an error to pass in an end index past the end of the array * @param endIndex the index to stop joining from (exclusive). It is * an error to pass in an end index past the end of the array * @return the joined String, null if null array input * @since 2.0 */ public static String join(Object[] array, char separator, int startIndex, int endIndex) { if (array == null) { return null; } int bufSize = (endIndex - startIndex); if (bufSize <= 0) { return EMPTY; } bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length()) + 1); StringBuffer buf = new StringBuffer(bufSize); for (int i = startIndex; i < endIndex; i++) { if (i > startIndex) { buf.append(separator); } if (array[i] != null) { buf.append(array[i]); } } return buf.toString(); } /** *

Joins the elements of the provided array into a single String * containing the provided list of elements.

*

*

No delimiter is added before or after the list. * A null separator is the same as an empty String (""). * Null objects or empty strings within the array are represented by * empty strings.

*

*

     * StringUtils.join(null, *)                = null
     * StringUtils.join([], *)                  = ""
     * StringUtils.join([null], *)              = ""
     * StringUtils.join(["a", "b", "c"], "--")  = "a--b--c"
     * StringUtils.join(["a", "b", "c"], null)  = "abc"
     * StringUtils.join(["a", "b", "c"], "")    = "abc"
     * StringUtils.join([null, "", "a"], ',')   = ",,a"
     * 
* * @param array the array of values to join together, may be null * @param separator the separator character to use, null treated as "" * @return the joined String, null if null array input */ public static String join(Object[] array, String separator) { if (array == null) { return null; } return join(array, separator, 0, array.length); } /** *

Joins the elements of the provided array into a single String * containing the provided list of elements.

*

*

No delimiter is added before or after the list. * A null separator is the same as an empty String (""). * Null objects or empty strings within the array are represented by * empty strings.

*

*

     * StringUtils.join(null, *)                = null
     * StringUtils.join([], *)                  = ""
     * StringUtils.join([null], *)              = ""
     * StringUtils.join(["a", "b", "c"], "--")  = "a--b--c"
     * StringUtils.join(["a", "b", "c"], null)  = "abc"
     * StringUtils.join(["a", "b", "c"], "")    = "abc"
     * StringUtils.join([null, "", "a"], ',')   = ",,a"
     * 
* * @param array the array of values to join together, may be null * @param separator the separator character to use, null treated as "" * @param startIndex the first index to start joining from. It is * an error to pass in an end index past the end of the array * @param endIndex the index to stop joining from (exclusive). It is * an error to pass in an end index past the end of the array * @return the joined String, null if null array input */ public static String join(Object[] array, String separator, int startIndex, int endIndex) { if (array == null) { return null; } if (separator == null) { separator = EMPTY; } // endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator)) // (Assuming that all Strings are roughly equally long) int bufSize = (endIndex - startIndex); if (bufSize <= 0) { return EMPTY; } bufSize *= ((array[startIndex] == null ? 16 : array[startIndex].toString().length()) + separator.length()); StringBuffer buf = new StringBuffer(bufSize); for (int i = startIndex; i < endIndex; i++) { if (i > startIndex) { buf.append(separator); } if (array[i] != null) { buf.append(array[i]); } } return buf.toString(); } /** *

Deletes all whitespaces from a String as defined by * {@link Character#isWhitespace(char)}.

*

*

     * StringUtils.deleteWhitespace(null)         = null
     * StringUtils.deleteWhitespace("")           = ""
     * StringUtils.deleteWhitespace("abc")        = "abc"
     * StringUtils.deleteWhitespace("   ab  c  ") = "abc"
     * 
* * @param str the String to delete whitespace from, may be null * @return the String without whitespaces, null if null String input */ public static String deleteWhitespace(String str) { if (isEmpty(str)) { return str; } int sz = str.length(); char[] chs = new char[sz]; int count = 0; for (int i = 0; i < sz; i++) { if (!Character.isWhitespace(str.charAt(i))) { chs[count++] = str.charAt(i); } } if (count == sz) { return str; } return new String(chs, 0, count); } // Remove //----------------------------------------------------------------------- /** *

Removes a substring only if it is at the begining of a source string, * otherwise returns the source string.

*

*

A null source string will return null. * An empty ("") source string will return the empty string. * A null search string will return the source string.

*

*

     * StringUtils.removeStart(null, *)      = null
     * StringUtils.removeStart("", *)        = ""
     * StringUtils.removeStart(*, null)      = *
     * StringUtils.removeStart("www.domain.com", "www.")   = "domain.com"
     * StringUtils.removeStart("domain.com", "www.")       = "domain.com"
     * StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com"
     * StringUtils.removeStart("abc", "")    = "abc"
     * 
* * @param str the source String to search, may be null * @param remove the String to search for and remove, may be null * @return the substring with the string removed if found, * null if null String input * @since 2.1 */ public static String removeStart(String str, String remove) { if (isEmpty(str) || isEmpty(remove)) { return str; } if (str.startsWith(remove)) { return str.substring(remove.length()); } return str; } /** *

Removes a substring only if it is at the end of a source string, * otherwise returns the source string.

*

*

A null source string will return null. * An empty ("") source string will return the empty string. * A null search string will return the source string.

*

*

     * StringUtils.removeEnd(null, *)      = null
     * StringUtils.removeEnd("", *)        = ""
     * StringUtils.removeEnd(*, null)      = *
     * StringUtils.removeEnd("www.domain.com", ".com.")  = "www.domain.com."
     * StringUtils.removeEnd("www.domain.com", ".com")   = "www.domain"
     * StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
     * StringUtils.removeEnd("abc", "")    = "abc"
     * 
* * @param str the source String to search, may be null * @param remove the String to search for and remove, may be null * @return the substring with the string removed if found, * null if null String input * @since 2.1 */ public static String removeEnd(String str, String remove) { if (isEmpty(str) || isEmpty(remove)) { return str; } if (str.endsWith(remove)) { return str.substring(0, str.length() - remove.length()); } return str; } /** *

Removes all occurances of a substring from within the source string.

*

*

A null source string will return null. * An empty ("") source string will return the empty string. * A null remove string will return the source string. * An empty ("") remove string will return the source string.

*

*

     * StringUtils.remove(null, *)        = null
     * StringUtils.remove("", *)          = ""
     * StringUtils.remove(*, null)        = *
     * StringUtils.remove(*, "")          = *
     * StringUtils.remove("queued", "ue") = "qd"
     * StringUtils.remove("queued", "zz") = "queued"
     * 
* * @param str the source String to search, may be null * @param remove the String to search for and remove, may be null * @return the substring with the string removed if found, * null if null String input * @since 2.1 */ public static String remove(String str, String remove) { if (isEmpty(str) || isEmpty(remove)) { return str; } return replace(str, remove, "", -1); } /** *

Removes all occurances of a character from within the source string.

*

*

A null source string will return null. * An empty ("") source string will return the empty string.

*

*

     * StringUtils.remove(null, *)       = null
     * StringUtils.remove("", *)         = ""
     * StringUtils.remove("queued", 'u') = "qeed"
     * StringUtils.remove("queued", 'z') = "queued"
     * 
* * @param str the source String to search, may be null * @param remove the char to search for and remove, may be null * @return the substring with the char removed if found, * null if null String input * @since 2.1 */ public static String remove(String str, char remove) { if (isEmpty(str) || str.indexOf(remove) == -1) { return str; } char[] chars = str.toCharArray(); int pos = 0; for (int i = 0; i < chars.length; i++) { if (chars[i] != remove) { chars[pos++] = chars[i]; } } return new String(chars, 0, pos); } // Replacing //----------------------------------------------------------------------- /** *

Replaces a String with another String inside a larger String, once.

*

*

A null reference passed to this method is a no-op.

*

*

     * StringUtils.replaceOnce(null, *, *)        = null
     * StringUtils.replaceOnce("", *, *)          = ""
     * StringUtils.replaceOnce("any", null, *)    = "any"
     * StringUtils.replaceOnce("any", *, null)    = "any"
     * StringUtils.replaceOnce("any", "", *)      = "any"
     * StringUtils.replaceOnce("aba", "a", null)  = "aba"
     * StringUtils.replaceOnce("aba", "a", "")    = "ba"
     * StringUtils.replaceOnce("aba", "a", "z")   = "zba"
     * 
* * @param text text to search and replace in, may be null * @param repl the String to search for, may be null * @param with the String to replace with, may be null * @return the text with any replacements processed, * null if null String input * @see #replace(String text, String repl, String with, int max) */ public static String replaceOnce(String text, String repl, String with) { return replace(text, repl, with, 1); } /** *

Replaces all occurrences of a String within another String.

*

*

A null reference passed to this method is a no-op.

*

*

     * StringUtils.replace(null, *, *)        = null
     * StringUtils.replace("", *, *)          = ""
     * StringUtils.replace("any", null, *)    = "any"
     * StringUtils.replace("any", *, null)    = "any"
     * StringUtils.replace("any", "", *)      = "any"
     * StringUtils.replace("aba", "a", null)  = "aba"
     * StringUtils.replace("aba", "a", "")    = "b"
     * StringUtils.replace("aba", "a", "z")   = "zbz"
     * 
* * @param text text to search and replace in, may be null * @param repl the String to search for, may be null * @param with the String to replace with, may be null * @return the text with any replacements processed, * null if null String input * @see #replace(String text, String repl, String with, int max) */ public static String replace(String text, String repl, String with) { return replace(text, repl, with, -1); } /** *

Replaces a String with another String inside a larger String, * for the first max values of the search String.

*

*

A null reference passed to this method is a no-op.

*

*

     * StringUtils.replace(null, *, *, *)         = null
     * StringUtils.replace("", *, *, *)           = ""
     * StringUtils.replace("any", null, *, *)     = "any"
     * StringUtils.replace("any", *, null, *)     = "any"
     * StringUtils.replace("any", "", *, *)       = "any"
     * StringUtils.replace("any", *, *, 0)        = "any"
     * StringUtils.replace("abaa", "a", null, -1) = "abaa"
     * StringUtils.replace("abaa", "a", "", -1)   = "b"
     * StringUtils.replace("abaa", "a", "z", 0)   = "abaa"
     * StringUtils.replace("abaa", "a", "z", 1)   = "zbaa"
     * StringUtils.replace("abaa", "a", "z", 2)   = "zbza"
     * StringUtils.replace("abaa", "a", "z", -1)  = "zbzz"
     * 
* * @param text text to search and replace in, may be null * @param repl the String to search for, may be null * @param with the String to replace with, may be null * @param max maximum number of values to replace, or -1 if no maximum * @return the text with any replacements processed, * null if null String input */ public static String replace(String text, String repl, String with, int max) { if (isEmpty(text) || isEmpty(repl) || with == null || max == 0) { return text; } int start = 0; int end = text.indexOf(repl, start); if (end == -1) { return text; } int replLength = repl.length(); int increase = with.length() - replLength; increase = (increase < 0 ? 0 : increase); increase *= (max < 0 ? 16 : (max > 64 ? 64 : max)); StringBuffer buf = new StringBuffer(text.length() + increase); while (end != -1) { buf.append(text.substring(start, end)).append(with); start = end + replLength; if (--max == 0) { break; } end = text.indexOf(repl, start); } buf.append(text.substring(start)); return buf.toString(); } // Replace, character based //----------------------------------------------------------------------- /** *

Replaces all occurrences of a character in a String with another. * This is a null-safe version of {@link String#replace(char, char)}.

*

*

A null string input returns null. * An empty ("") string input returns an empty string.

*

*

     * StringUtils.replaceChars(null, *, *)        = null
     * StringUtils.replaceChars("", *, *)          = ""
     * StringUtils.replaceChars("abcba", 'b', 'y') = "aycya"
     * StringUtils.replaceChars("abcba", 'z', 'y') = "abcba"
     * 
* * @param str String to replace characters in, may be null * @param searchChar the character to search for, may be null * @param replaceChar the character to replace, may be null * @return modified String, null if null string input * @since 2.0 */ public static String replaceChars(String str, char searchChar, char replaceChar) { if (str == null) { return null; } return str.replace(searchChar, replaceChar); } /** *

Replaces multiple characters in a String in one go. * This method can also be used to delete characters.

*

*

For example:
* replaceChars("hello", "ho", "jy") = jelly.

*

*

A null string input returns null. * An empty ("") string input returns an empty string. * A null or empty set of search characters returns the input string.

*

*

The length of the search characters should normally equal the length * of the replace characters. * If the search characters is longer, then the extra search characters * are deleted. * If the search characters is shorter, then the extra replace characters * are ignored.

*

*

     * StringUtils.replaceChars(null, *, *)           = null
     * StringUtils.replaceChars("", *, *)             = ""
     * StringUtils.replaceChars("abc", null, *)       = "abc"
     * StringUtils.replaceChars("abc", "", *)         = "abc"
     * StringUtils.replaceChars("abc", "b", null)     = "ac"
     * StringUtils.replaceChars("abc", "b", "")       = "ac"
     * StringUtils.replaceChars("abcba", "bc", "yz")  = "ayzya"
     * StringUtils.replaceChars("abcba", "bc", "y")   = "ayya"
     * StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya"
     * 
* * @param str String to replace characters in, may be null * @param searchChars a set of characters to search for, may be null * @param replaceChars a set of characters to replace, may be null * @return modified String, null if null string input * @since 2.0 */ public static String replaceChars(String str, String searchChars, String replaceChars) { if (isEmpty(str) || isEmpty(searchChars)) { return str; } if (replaceChars == null) { replaceChars = ""; } boolean modified = false; int replaceCharsLength = replaceChars.length(); int strLength = str.length(); StringBuffer buf = new StringBuffer(strLength); for (int i = 0; i < strLength; i++) { char ch = str.charAt(i); int index = searchChars.indexOf(ch); if (index >= 0) { modified = true; if (index < replaceCharsLength) { buf.append(replaceChars.charAt(index)); } } else { buf.append(ch); } } if (modified) { return buf.toString(); } else { return str; } } // Overlay //----------------------------------------------------------------------- /** *

Overlays part of a String with another String.

*

*

     * StringUtils.overlayString(null, *, *, *)           = NullPointerException
     * StringUtils.overlayString(*, null, *, *)           = NullPointerException
     * StringUtils.overlayString("", "abc", 0, 0)         = "abc"
     * StringUtils.overlayString("abcdef", null, 2, 4)    = "abef"
     * StringUtils.overlayString("abcdef", "", 2, 4)      = "abef"
     * StringUtils.overlayString("abcdef", "zzzz", 2, 4)  = "abzzzzef"
     * StringUtils.overlayString("abcdef", "zzzz", 4, 2)  = "abcdzzzzcdef"
     * StringUtils.overlayString("abcdef", "zzzz", -1, 4) = IndexOutOfBoundsException
     * StringUtils.overlayString("abcdef", "zzzz", 2, 8)  = IndexOutOfBoundsException
     * 
* * @param text the String to do overlaying in, may be null * @param overlay the String to overlay, may be null * @param start the position to start overlaying at, must be valid * @param end the position to stop overlaying before, must be valid * @return overlayed String, null if null String input * @throws NullPointerException if text or overlay is null * @throws IndexOutOfBoundsException if either position is invalid * @deprecated Use better named {@link #overlay(String, String, int, int)} instead. * Method will be removed in Commons Lang 3.0. */ public static String overlayString(String text, String overlay, int start, int end) { return new StringBuffer(start + overlay.length() + text.length() - end + 1).append(text.substring(0, start)).append(overlay).append(text.substring(end)).toString(); } /** *

Overlays part of a String with another String.

*

*

A null string input returns null. * A negative index is treated as zero. * An index greater than the string length is treated as the string length. * The start index is always the smaller of the two indices.

*

*

     * StringUtils.overlay(null, *, *, *)            = null
     * StringUtils.overlay("", "abc", 0, 0)          = "abc"
     * StringUtils.overlay("abcdef", null, 2, 4)     = "abef"
     * StringUtils.overlay("abcdef", "", 2, 4)       = "abef"
     * StringUtils.overlay("abcdef", "", 4, 2)       = "abef"
     * StringUtils.overlay("abcdef", "zzzz", 2, 4)   = "abzzzzef"
     * StringUtils.overlay("abcdef", "zzzz", 4, 2)   = "abzzzzef"
     * StringUtils.overlay("abcdef", "zzzz", -1, 4)  = "zzzzef"
     * StringUtils.overlay("abcdef", "zzzz", 2, 8)   = "abzzzz"
     * StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
     * StringUtils.overlay("abcdef", "zzzz", 8, 10)  = "abcdefzzzz"
     * 
* * @param str the String to do overlaying in, may be null * @param overlay the String to overlay, may be null * @param start the position to start overlaying at * @param end the position to stop overlaying before * @return overlayed String, null if null String input * @since 2.0 */ public static String overlay(String str, String overlay, int start, int end) { if (str == null) { return null; } if (overlay == null) { overlay = EMPTY; } int len = str.length(); if (start < 0) { start = 0; } if (start > len) { start = len; } if (end < 0) { end = 0; } if (end > len) { end = len; } if (start > end) { int temp = start; start = end; end = temp; } return new StringBuffer(len + start - end + overlay.length() + 1).append(str.substring(0, start)).append(overlay).append(str.substring(end)).toString(); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy