/*
* Copyright (c) 2002-2012 Alibaba Group Holding Limited.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.citrus.util;
import static com.alibaba.citrus.util.ArrayUtil.*;
import static com.alibaba.citrus.util.BasicConstant.*;
import static com.alibaba.citrus.util.CollectionUtil.*;
import static com.alibaba.citrus.util.ObjectUtil.*;
import java.util.Formatter;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 有关字符串处理的工具类。
* <p>
* 这个类中的每个方法都可以“安全”地处理<code>null</code>,而不会抛出<code>NullPointerException</code>。
* </p>
*
* @author Michael Zhou
*/
public class StringUtil {
// ==========================================================================
// 基本函数。
//
// 注:对于大小写敏感的isEquals方法,请使用ObjectUtil.isEquals。
// ==========================================================================
/**
* 取得字符串的长度。
*
* @param str 要取长度的字符串
* @return 如果字符串为<code>null</code>,则返回<code>0</code>。否则返回字符串的长度。
*/
public static int getLength(String str) {
return str == null ? 0 : str.length();
}
/**
* 比较两个字符串(大小写不敏感)。
* <p/>
* <pre>
* StringUtil.equalsIgnoreCase(null, null) = true
* StringUtil.equalsIgnoreCase(null, "abc") = false
* StringUtil.equalsIgnoreCase("abc", null) = false
* StringUtil.equalsIgnoreCase("abc", "abc") = true
* StringUtil.equalsIgnoreCase("abc", "ABC") = true
* </pre>
*
* @param str1 要比较的字符串1
* @param str2 要比较的字符串2
* @return 如果两个字符串相同,或者都是<code>null</code>,则返回<code>true</code>
*/
public static boolean isEqualsIgnoreCase(String str1, String str2) {
if (str1 == null) {
return str2 == null;
}
return str1.equalsIgnoreCase(str2);
}
// ==========================================================================
// 判空函数。
//
// 以下方法用来判定一个字符串是否为:
// 1. null
// 2. empty - ""
// 3. blank - "全部是空白" - 空白由Character.isWhitespace所定义。
// ==========================================================================
/**
* 检查字符串是否为<code>null</code>或空字符串<code>""</code>。
* <p/>
* <pre>
* StringUtil.isEmpty(null) = true
* StringUtil.isEmpty("") = true
* StringUtil.isEmpty(" ") = false
* StringUtil.isEmpty("bob") = false
* StringUtil.isEmpty(" bob ") = false
* </pre>
*
* @param str 要检查的字符串
* @return 如果为空, 则返回<code>true</code>
*/
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
/**
* 检查字符串是否是空白:<code>null</code>、空字符串<code>""</code>或只有空白字符。
* <p/>
* <pre>
* StringUtil.isBlank(null) = true
* StringUtil.isBlank("") = true
* StringUtil.isBlank(" ") = true
* StringUtil.isBlank("bob") = false
* StringUtil.isBlank(" bob ") = false
* </pre>
*
* @param str 要检查的字符串
* @return 如果为空白, 则返回<code>true</code>
*/
public static boolean isBlank(String str) {
int length;
if (str == null || (length = str.length()) == 0) {
return true;
}
for (int i = 0; i < length; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return false;
}
}
return true;
}
// ==========================================================================
// 默认值函数。
//
// 当字符串为empty或blank时,将字符串转换成指定的默认字符串。
// 注:判断字符串为null时,可用更通用的ObjectUtil.defaultIfNull。
// ==========================================================================
/**
* 如果字符串是<code>null</code>或空字符串<code>""</code>,则返回指定默认字符串,否则返回字符串本身。
* <p/>
* <pre>
* StringUtil.defaultIfEmpty(null, "default") = "default"
* StringUtil.defaultIfEmpty("", "default") = "default"
* StringUtil.defaultIfEmpty(" ", "default") = " "
* StringUtil.defaultIfEmpty("bat", "default") = "bat"
* </pre>
*
* @param str 要转换的字符串
* @param defaultStr 默认字符串
* @return 字符串本身或指定的默认字符串
*/
public static String defaultIfEmpty(String str, String defaultStr) {
return str == null || str.length() == 0 ? defaultStr : str;
}
/**
* 如果字符串是<code>null</code>或空字符串<code>""</code>,则返回指定默认字符串,否则返回字符串本身。
* <p/>
* <pre>
* StringUtil.defaultIfBlank(null, "default") = "default"
* StringUtil.defaultIfBlank("", "default") = "default"
* StringUtil.defaultIfBlank(" ", "default") = "default"
* StringUtil.defaultIfBlank("bat", "default") = "bat"
* </pre>
*
* @param str 要转换的字符串
* @param defaultStr 默认字符串
* @return 字符串本身或指定的默认字符串
*/
public static String defaultIfBlank(String str, String defaultStr) {
return isBlank(str) ? defaultStr : str;
}
// ==========================================================================
// 去空白的函数。
//
// 以下方法用来除去一个字串首尾的空白。
// ==========================================================================
/**
* 除去字符串头尾部的空白,如果字符串是<code>null</code>,依然返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.trim(null) = null
* StringUtil.trim("") = ""
* StringUtil.trim(" ") = ""
* StringUtil.trim("abc") = "abc"
* StringUtil.trim(" abc ") = "abc"
* </pre>
*
* @param str 要处理的字符串
* @return 除去空白的字符串,如果原字串为<code>null</code>,则返回<code>null</code>
*/
public static String trim(String str) {
return str == null ? null : str.trim();
}
/**
* 除去字符串头尾部的空白,如果结果字符串是空字符串<code>""</code>,则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.trimToNull(null) = null
* StringUtil.trimToNull("") = null
* StringUtil.trimToNull(" ") = null
* StringUtil.trimToNull("abc") = "abc"
* StringUtil.trimToNull(" abc ") = "abc"
* </pre>
*
* @param str 要处理的字符串
* @return 除去空白的字符串,如果原字串为<code>null</code>或结果字符串为<code>""</code>,则返回
* <code>null</code>
*/
public static String trimToNull(String str) {
if (str == null) {
return null;
}
String result = str.trim();
if (result == null || result.length() == 0) {
return null;
}
return result;
}
/**
* 除去字符串头尾部的空白,如果字符串是<code>null</code>,则返回空字符串<code>""</code>。
* <p/>
* <pre>
* StringUtil.trimToEmpty(null) = ""
* StringUtil.trimToEmpty("") = ""
* StringUtil.trimToEmpty(" ") = ""
* StringUtil.trimToEmpty("abc") = "abc"
* StringUtil.trimToEmpty(" abc ") = "abc"
* </pre>
*
* @param str 要处理的字符串
* @return 除去空白的字符串,如果原字串为<code>null</code>或结果字符串为<code>""</code>,则返回
* <code>null</code>
*/
public static String trimToEmpty(String str) {
if (str == null) {
return EMPTY_STRING;
}
return str.trim();
}
/**
* 除去字符串头尾部的指定字符,如果字符串是<code>null</code>,依然返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.trim(null, *) = null
* StringUtil.trim("", *) = ""
* StringUtil.trim("abc", null) = "abc"
* StringUtil.trim(" abc", null) = "abc"
* StringUtil.trim("abc ", null) = "abc"
* StringUtil.trim(" abc ", null) = "abc"
* StringUtil.trim(" abcyx", "xyz") = " abc"
* </pre>
*
* @param str 要处理的字符串
* @param stripChars 要除去的字符,如果为<code>null</code>表示除去空白字符
* @return 除去指定字符后的的字符串,如果原字串为<code>null</code>,则返回<code>null</code>
*/
public static String trim(String str, String stripChars) {
return trim(str, stripChars, 0);
}
/**
* 除去字符串头部的空白,如果字符串是<code>null</code>,则返回<code>null</code>。
* <p>
* 注意,和<code>String.trim</code>不同,此方法使用<code>Character.isWhitespace</code>
* 来判定空白, 因而可以除去英文字符集之外的其它空白,如中文空格。
* <p/>
* <pre>
* StringUtil.trimStart(null) = null
* StringUtil.trimStart("") = ""
* StringUtil.trimStart("abc") = "abc"
* StringUtil.trimStart(" abc") = "abc"
* StringUtil.trimStart("abc ") = "abc "
* StringUtil.trimStart(" abc ") = "abc "
* </pre>
* <p/>
* </p>
*
* @param str 要处理的字符串
* @return 除去空白的字符串,如果原字串为<code>null</code>或结果字符串为<code>""</code>,则返回
* <code>null</code>
*/
public static String trimStart(String str) {
return trim(str, null, -1);
}
/**
* 除去字符串头部的指定字符,如果字符串是<code>null</code>,依然返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.trimStart(null, *) = null
* StringUtil.trimStart("", *) = ""
* StringUtil.trimStart("abc", "") = "abc"
* StringUtil.trimStart("abc", null) = "abc"
* StringUtil.trimStart(" abc", null) = "abc"
* StringUtil.trimStart("abc ", null) = "abc "
* StringUtil.trimStart(" abc ", null) = "abc "
* StringUtil.trimStart("yxabc ", "xyz") = "abc "
* </pre>
*
* @param str 要处理的字符串
* @param stripChars 要除去的字符,如果为<code>null</code>表示除去空白字符
* @return 除去指定字符后的的字符串,如果原字串为<code>null</code>,则返回<code>null</code>
*/
public static String trimStart(String str, String stripChars) {
return trim(str, stripChars, -1);
}
/**
* 除去字符串尾部的空白,如果字符串是<code>null</code>,则返回<code>null</code>。
* <p>
* 注意,和<code>String.trim</code>不同,此方法使用<code>Character.isWhitespace</code>
* 来判定空白, 因而可以除去英文字符集之外的其它空白,如中文空格。
* <p/>
* <pre>
* StringUtil.trimEnd(null) = null
* StringUtil.trimEnd("") = ""
* StringUtil.trimEnd("abc") = "abc"
* StringUtil.trimEnd(" abc") = " abc"
* StringUtil.trimEnd("abc ") = "abc"
* StringUtil.trimEnd(" abc ") = " abc"
* </pre>
* <p/>
* </p>
*
* @param str 要处理的字符串
* @return 除去空白的字符串,如果原字串为<code>null</code>或结果字符串为<code>""</code>,则返回
* <code>null</code>
*/
public static String trimEnd(String str) {
return trim(str, null, 1);
}
/**
* 除去字符串尾部的指定字符,如果字符串是<code>null</code>,依然返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.trimEnd(null, *) = null
* StringUtil.trimEnd("", *) = ""
* StringUtil.trimEnd("abc", "") = "abc"
* StringUtil.trimEnd("abc", null) = "abc"
* StringUtil.trimEnd(" abc", null) = " abc"
* StringUtil.trimEnd("abc ", null) = "abc"
* StringUtil.trimEnd(" abc ", null) = " abc"
* StringUtil.trimEnd(" abcyx", "xyz") = " abc"
* </pre>
*
* @param str 要处理的字符串
* @param stripChars 要除去的字符,如果为<code>null</code>表示除去空白字符
* @return 除去指定字符后的的字符串,如果原字串为<code>null</code>,则返回<code>null</code>
*/
public static String trimEnd(String str, String stripChars) {
return trim(str, stripChars, 1);
}
/**
* 除去字符串头尾部的空白,如果结果字符串是空字符串<code>""</code>,则返回<code>null</code>。
* <p>
* 注意,和<code>String.trim</code>不同,此方法使用<code>Character.isWhitespace</code>
* 来判定空白, 因而可以除去英文字符集之外的其它空白,如中文空格。
* <p/>
* <pre>
* StringUtil.trim(null, *) = null
* StringUtil.trim("", *) = null
* StringUtil.trim("abc", null) = "abc"
* StringUtil.trim(" abc", null) = "abc"
* StringUtil.trim("abc ", null) = "abc"
* StringUtil.trim(" abc ", null) = "abc"
* StringUtil.trim(" abcyx", "xyz") = " abc"
* </pre>
* <p/>
* </p>
*
* @param str 要处理的字符串
* @param stripChars 要除去的字符,如果为<code>null</code>表示除去空白字符
* @return 除去空白的字符串,如果原字串为<code>null</code>或结果字符串为<code>""</code>,则返回
* <code>null</code>
*/
public static String trimToNull(String str, String stripChars) {
String result = trim(str, stripChars);
if (result == null || result.length() == 0) {
return null;
}
return result;
}
/**
* 除去字符串头尾部的空白,如果字符串是<code>null</code>,则返回空字符串<code>""</code>。
* <p>
* 注意,和<code>String.trim</code>不同,此方法使用<code>Character.isWhitespace</code>
* 来判定空白, 因而可以除去英文字符集之外的其它空白,如中文空格。
* <p/>
* <pre>
* StringUtil.trim(null, *) = ""
* StringUtil.trim("", *) = ""
* StringUtil.trim("abc", null) = "abc"
* StringUtil.trim(" abc", null) = "abc"
* StringUtil.trim("abc ", null) = "abc"
* StringUtil.trim(" abc ", null) = "abc"
* StringUtil.trim(" abcyx", "xyz") = " abc"
* </pre>
* <p/>
* </p>
*
* @param str 要处理的字符串
* @return 除去空白的字符串,如果原字串为<code>null</code>或结果字符串为<code>""</code>,则返回
* <code>null</code>
*/
public static String trimToEmpty(String str, String stripChars) {
String result = trim(str, stripChars);
if (result == null) {
return EMPTY_STRING;
}
return result;
}
/**
* 除去字符串头尾部的指定字符,如果字符串是<code>null</code>,依然返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.trim(null, *) = null
* StringUtil.trim("", *) = ""
* StringUtil.trim("abc", null) = "abc"
* StringUtil.trim(" abc", null) = "abc"
* StringUtil.trim("abc ", null) = "abc"
* StringUtil.trim(" abc ", null) = "abc"
* StringUtil.trim(" abcyx", "xyz") = " abc"
* </pre>
*
* @param str 要处理的字符串
* @param stripChars 要除去的字符,如果为<code>null</code>表示除去空白字符
* @param mode <code>-1</code>表示trimStart,<code>0</code>表示trim全部,
* <code>1</code>表示trimEnd
* @return 除去指定字符后的的字符串,如果原字串为<code>null</code>,则返回<code>null</code>
*/
private static String trim(String str, String stripChars, int mode) {
if (str == null) {
return null;
}
int length = str.length();
int start = 0;
int end = length;
// 扫描字符串头部
if (mode <= 0) {
if (stripChars == null) {
while (start < end && Character.isWhitespace(str.charAt(start))) {
start++;
}
} else if (stripChars.length() == 0) {
return str;
} else {
while (start < end && stripChars.indexOf(str.charAt(start)) != -1) {
start++;
}
}
}
// 扫描字符串尾部
if (mode >= 0) {
if (stripChars == null) {
while (start < end && Character.isWhitespace(str.charAt(end - 1))) {
end--;
}
} else if (stripChars.length() == 0) {
return str;
} else {
while (start < end && stripChars.indexOf(str.charAt(end - 1)) != -1) {
end--;
}
}
}
if (start > 0 || end < length) {
return str.substring(start, end);
}
return str;
}
// ==========================================================================
// 大小写转换。
// ==========================================================================
/**
* 将字符串的首字符转成大写(<code>Character.toTitleCase</code>),其它字符不变。
* <p>
* 如果字符串是<code>null</code>则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.capitalize(null) = null
* StringUtil.capitalize("") = ""
* StringUtil.capitalize("cat") = "Cat"
* StringUtil.capitalize("cAt") = "CAt"
* </pre>
* <p/>
* </p>
*
* @param str 要转换的字符串
* @return 首字符为大写的字符串,如果原字符串为<code>null</code>,则返回<code>null</code>
*/
public static String capitalize(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
return new StringBuilder(strLen).append(Character.toTitleCase(str.charAt(0))).append(str.substring(1))
.toString();
}
/**
* 将字符串的首字符转成小写,其它字符不变。
* <p>
* 如果字符串是<code>null</code>则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.uncapitalize(null) = null
* StringUtil.uncapitalize("") = ""
* StringUtil.uncapitalize("Cat") = "cat"
* StringUtil.uncapitalize("CAT") = "CAT"
* </pre>
* <p/>
* </p>
*
* @param str 要转换的字符串
* @return 首字符为小写的字符串,如果原字符串为<code>null</code>,则返回<code>null</code>
*/
public static String uncapitalize(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
if (strLen > 1 && Character.isUpperCase(str.charAt(1)) && Character.isUpperCase(str.charAt(0))) {
return str;
}
return new StringBuilder(strLen).append(Character.toLowerCase(str.charAt(0))).append(str.substring(1))
.toString();
}
/**
* 反转字符串的大小写。
* <p>
* 如果字符串是<code>null</code>则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.swapCase(null) = null
* StringUtil.swapCase("") = ""
* StringUtil.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
* </pre>
* <p/>
* </p>
*
* @param str 要转换的字符串
* @return 大小写被反转的字符串,如果原字符串为<code>null</code>,则返回<code>null</code>
*/
public static String swapCase(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
StringBuilder buffer = new StringBuilder(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();
}
/**
* 将字符串转换成大写。
* <p>
* 如果字符串是<code>null</code>则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.toUpperCase(null) = null
* StringUtil.toUpperCase("") = ""
* StringUtil.toUpperCase("aBc") = "ABC"
* </pre>
* <p/>
* </p>
*
* @param str 要转换的字符串
* @return 大写字符串,如果原字符串为<code>null</code>,则返回<code>null</code>
*/
public static String toUpperCase(String str) {
if (str == null) {
return null;
}
return str.toUpperCase();
}
/**
* 将字符串转换成小写。
* <p>
* 如果字符串是<code>null</code>则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.toLowerCase(null) = null
* StringUtil.toLowerCase("") = ""
* StringUtil.toLowerCase("aBc") = "abc"
* </pre>
* <p/>
* </p>
*
* @param str 要转换的字符串
* @return 大写字符串,如果原字符串为<code>null</code>,则返回<code>null</code>
*/
public static String toLowerCase(String str) {
if (str == null) {
return null;
}
return str.toLowerCase();
}
/**
* 将字符串转换成camel case。
* <p>
* 如果字符串是<code>null</code>则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.toCamelCase(null) = null
* StringUtil.toCamelCase("") = ""
* StringUtil.toCamelCase("aBc") = "aBc"
* StringUtil.toCamelCase("aBc def") = "aBcDef"
* StringUtil.toCamelCase("aBc def_ghi") = "aBcDefGhi"
* StringUtil.toCamelCase("aBc def_ghi 123") = "aBcDefGhi123"
* </pre>
* <p/>
* </p>
* <p>
* 此方法会保留除了下划线和空白以外的所有分隔符。
* </p>
*
* @param str 要转换的字符串
* @return camel case字符串,如果原字符串为<code>null</code>,则返回<code>null</code>
*/
public static String toCamelCase(String str) {
return new WordTokenizer() {
@Override
protected void startSentence(StringBuilder buffer, char ch) {
buffer.append(Character.toLowerCase(ch));
}
@Override
protected void startWord(StringBuilder buffer, char ch) {
if (!isDelimiter(buffer.charAt(buffer.length() - 1))) {
buffer.append(Character.toUpperCase(ch));
} else {
buffer.append(Character.toLowerCase(ch));
}
}
@Override
protected void inWord(StringBuilder buffer, char ch) {
buffer.append(Character.toLowerCase(ch));
}
@Override
protected void startDigitSentence(StringBuilder buffer, char ch) {
buffer.append(ch);
}
@Override
protected void startDigitWord(StringBuilder buffer, char ch) {
buffer.append(ch);
}
@Override
protected void inDigitWord(StringBuilder buffer, char ch) {
buffer.append(ch);
}
@Override
protected void inDelimiter(StringBuilder buffer, char ch) {
if (ch != UNDERSCORE) {
buffer.append(ch);
}
}
}.parse(str);
}
/**
* 将字符串转换成pascal case。
* <p>
* 如果字符串是<code>null</code>则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.toPascalCase(null) = null
* StringUtil.toPascalCase("") = ""
* StringUtil.toPascalCase("aBc") = "ABc"
* StringUtil.toPascalCase("aBc def") = "ABcDef"
* StringUtil.toPascalCase("aBc def_ghi") = "ABcDefGhi"
* StringUtil.toPascalCase("aBc def_ghi 123") = "aBcDefGhi123"
* </pre>
* <p/>
* </p>
* <p>
* 此方法会保留除了下划线和空白以外的所有分隔符。
* </p>
*
* @param str 要转换的字符串
* @return pascal case字符串,如果原字符串为<code>null</code>,则返回<code>null</code>
*/
public static String toPascalCase(String str) {
return new WordTokenizer() {
@Override
protected void startSentence(StringBuilder buffer, char ch) {
buffer.append(Character.toUpperCase(ch));
}
@Override
protected void startWord(StringBuilder buffer, char ch) {
buffer.append(Character.toUpperCase(ch));
}
@Override
protected void inWord(StringBuilder buffer, char ch) {
buffer.append(Character.toLowerCase(ch));
}
@Override
protected void startDigitSentence(StringBuilder buffer, char ch) {
buffer.append(ch);
}
@Override
protected void startDigitWord(StringBuilder buffer, char ch) {
buffer.append(ch);
}
@Override
protected void inDigitWord(StringBuilder buffer, char ch) {
buffer.append(ch);
}
@Override
protected void inDelimiter(StringBuilder buffer, char ch) {
if (ch != UNDERSCORE) {
buffer.append(ch);
}
}
}.parse(str);
}
/**
* 将字符串转换成下划线分隔的大写字符串。
* <p>
* 如果字符串是<code>null</code>则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.toUpperCaseWithUnderscores(null) = null
* StringUtil.toUpperCaseWithUnderscores("") = ""
* StringUtil.toUpperCaseWithUnderscores("aBc") = "A_BC"
* StringUtil.toUpperCaseWithUnderscores("aBc def") = "A_BC_DEF"
* StringUtil.toUpperCaseWithUnderscores("aBc def_ghi") = "A_BC_DEF_GHI"
* StringUtil.toUpperCaseWithUnderscores("aBc def_ghi 123") = "A_BC_DEF_GHI_123"
* StringUtil.toUpperCaseWithUnderscores("__a__Bc__") = "__A__BC__"
* </pre>
* <p/>
* </p>
* <p>
* 此方法会保留除了空白以外的所有分隔符。
* </p>
*
* @param str 要转换的字符串
* @return 下划线分隔的大写字符串,如果原字符串为<code>null</code>,则返回<code>null</code>
*/
public static String toUpperCaseWithUnderscores(String str) {
return new WordTokenizer() {
@Override
protected void startSentence(StringBuilder buffer, char ch) {
buffer.append(Character.toUpperCase(ch));
}
@Override
protected void startWord(StringBuilder buffer, char ch) {
if (!isDelimiter(buffer.charAt(buffer.length() - 1))) {
buffer.append(UNDERSCORE);
}
buffer.append(Character.toUpperCase(ch));
}
@Override
protected void inWord(StringBuilder buffer, char ch) {
buffer.append(Character.toUpperCase(ch));
}
@Override
protected void startDigitSentence(StringBuilder buffer, char ch) {
buffer.append(ch);
}
@Override
protected void startDigitWord(StringBuilder buffer, char ch) {
if (!isDelimiter(buffer.charAt(buffer.length() - 1))) {
buffer.append(UNDERSCORE);
}
buffer.append(ch);
}
@Override
protected void inDigitWord(StringBuilder buffer, char ch) {
buffer.append(ch);
}
@Override
protected void inDelimiter(StringBuilder buffer, char ch) {
buffer.append(ch);
}
}.parse(str);
}
/**
* 将字符串转换成下划线分隔的小写字符串。
* <p>
* 如果字符串是<code>null</code>则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.toLowerCaseWithUnderscores(null) = null
* StringUtil.toLowerCaseWithUnderscores("") = ""
* StringUtil.toLowerCaseWithUnderscores("aBc") = "a_bc"
* StringUtil.toLowerCaseWithUnderscores("aBc def") = "a_bc_def"
* StringUtil.toLowerCaseWithUnderscores("aBc def_ghi") = "a_bc_def_ghi"
* StringUtil.toLowerCaseWithUnderscores("aBc def_ghi 123") = "a_bc_def_ghi_123"
* StringUtil.toLowerCaseWithUnderscores("__a__Bc__") = "__a__bc__"
* </pre>
* <p/>
* </p>
* <p>
* 此方法会保留除了空白以外的所有分隔符。
* </p>
*
* @param str 要转换的字符串
* @return 下划线分隔的小写字符串,如果原字符串为<code>null</code>,则返回<code>null</code>
*/
public static String toLowerCaseWithUnderscores(String str) {
return new WordTokenizer() {
@Override
protected void startSentence(StringBuilder buffer, char ch) {
buffer.append(Character.toLowerCase(ch));
}
@Override
protected void startWord(StringBuilder buffer, char ch) {
if (!isDelimiter(buffer.charAt(buffer.length() - 1))) {
buffer.append(UNDERSCORE);
}
buffer.append(Character.toLowerCase(ch));
}
@Override
protected void inWord(StringBuilder buffer, char ch) {
buffer.append(Character.toLowerCase(ch));
}
@Override
protected void startDigitSentence(StringBuilder buffer, char ch) {
buffer.append(ch);
}
@Override
protected void startDigitWord(StringBuilder buffer, char ch) {
if (!isDelimiter(buffer.charAt(buffer.length() - 1))) {
buffer.append(UNDERSCORE);
}
buffer.append(ch);
}
@Override
protected void inDigitWord(StringBuilder buffer, char ch) {
buffer.append(ch);
}
@Override
protected void inDelimiter(StringBuilder buffer, char ch) {
buffer.append(ch);
}
}.parse(str);
}
/**
* 解析出下列语法所构成的<code>SENTENCE</code>。
* <p/>
* <pre>
* SENTENCE = WORD (DELIMITER* WORD)*
*
* WORD = UPPER_CASE_WORD | LOWER_CASE_WORD | TITLE_CASE_WORD | DIGIT_WORD
*
* UPPER_CASE_WORD = UPPER_CASE_LETTER+
* LOWER_CASE_WORD = LOWER_CASE_LETTER+
* TITLE_CASE_WORD = UPPER_CASE_LETTER LOWER_CASE_LETTER+
* DIGIT_WORD = DIGIT+
*
* UPPER_CASE_LETTER = Character.isUpperCase()
* LOWER_CASE_LETTER = Character.isLowerCase()
* DIGIT = Character.isDigit()
* NON_LETTER_DIGIT = !Character.isUpperCase() && !Character.isLowerCase() && !Character.isDigit()
*
* DELIMITER = WHITESPACE | NON_LETTER_DIGIT
* </pre>
*/
private abstract static class WordTokenizer {
protected static final char UNDERSCORE = '_';
/** Parse sentence。 */
public String parse(String str) {
if (StringUtil.isEmpty(str)) {
return str;
}
int length = str.length();
StringBuilder buffer = new StringBuilder(length);
for (int index = 0; index < length; index++) {
char ch = str.charAt(index);
// 忽略空白。
if (Character.isWhitespace(ch)) {
continue;
}
// 大写字母开始:UpperCaseWord或是TitleCaseWord。
if (Character.isUpperCase(ch)) {
int wordIndex = index + 1;
while (wordIndex < length) {
char wordChar = str.charAt(wordIndex);
if (Character.isUpperCase(wordChar)) {
wordIndex++;
} else if (Character.isLowerCase(wordChar)) {
wordIndex--;
break;
} else {
break;
}
}
// 1. wordIndex == length,说明最后一个字母为大写,以upperCaseWord处理之。
// 2. wordIndex == index,说明index处为一个titleCaseWord。
// 3. wordIndex > index,说明index到wordIndex - 1处全部是大写,以upperCaseWord处理。
if (wordIndex == length || wordIndex > index) {
index = parseUpperCaseWord(buffer, str, index, wordIndex);
} else {
index = parseTitleCaseWord(buffer, str, index);
}
continue;
}
// 小写字母开始:LowerCaseWord。
if (Character.isLowerCase(ch)) {
index = parseLowerCaseWord(buffer, str, index);
continue;
}
// 数字开始:DigitWord。
if (Character.isDigit(ch)) {
index = parseDigitWord(buffer, str, index);
continue;
}
// 非字母数字开始:Delimiter。
inDelimiter(buffer, ch);
}
return buffer.toString();
}
private int parseUpperCaseWord(StringBuilder buffer, String str, int index, int length) {
char ch = str.charAt(index++);
// 首字母,必然存在且为大写。
if (buffer.length() == 0) {
startSentence(buffer, ch);
} else {
startWord(buffer, ch);
}
// 后续字母,必为小写。
for (; index < length; index++) {
ch = str.charAt(index);
inWord(buffer, ch);
}
return index - 1;
}
private int parseLowerCaseWord(StringBuilder buffer, String str, int index) {
char ch = str.charAt(index++);
// 首字母,必然存在且为小写。
if (buffer.length() == 0) {
startSentence(buffer, ch);
} else {
startWord(buffer, ch);
}
// 后续字母,必为小写。
int length = str.length();
for (; index < length; index++) {
ch = str.charAt(index);
if (Character.isLowerCase(ch)) {
inWord(buffer, ch);
} else {
break;
}
}
return index - 1;
}
private int parseTitleCaseWord(StringBuilder buffer, String str, int index) {
char ch = str.charAt(index++);
// 首字母,必然存在且为大写。
if (buffer.length() == 0) {
startSentence(buffer, ch);
} else {
startWord(buffer, ch);
}
// 后续字母,必为小写。
int length = str.length();
for (; index < length; index++) {
ch = str.charAt(index);
if (Character.isLowerCase(ch)) {
inWord(buffer, ch);
} else {
break;
}
}
return index - 1;
}
private int parseDigitWord(StringBuilder buffer, String str, int index) {
char ch = str.charAt(index++);
// 首字符,必然存在且为数字。
if (buffer.length() == 0) {
startDigitSentence(buffer, ch);
} else {
startDigitWord(buffer, ch);
}
// 后续字符,必为数字。
int length = str.length();
for (; index < length; index++) {
ch = str.charAt(index);
if (Character.isDigit(ch)) {
inDigitWord(buffer, ch);
} else {
break;
}
}
return index - 1;
}
protected boolean isDelimiter(char ch) {
return !Character.isUpperCase(ch) && !Character.isLowerCase(ch) && !Character.isDigit(ch);
}
protected abstract void startSentence(StringBuilder buffer, char ch);
protected abstract void startWord(StringBuilder buffer, char ch);
protected abstract void inWord(StringBuilder buffer, char ch);
protected abstract void startDigitSentence(StringBuilder buffer, char ch);
protected abstract void startDigitWord(StringBuilder buffer, char ch);
protected abstract void inDigitWord(StringBuilder buffer, char ch);
protected abstract void inDelimiter(StringBuilder buffer, char ch);
}
// ==========================================================================
// 字符串分割函数。
//
// 将字符串按指定分隔符分割。
// ==========================================================================
/**
* 将字符串按指定字符分割。
* <p>
* 分隔符不会出现在目标数组中,连续的分隔符就被看作一个。如果字符串为<code>null</code>,则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.split(null, *) = null
* StringUtil.split("", *) = []
* StringUtil.split("a.b.c", '.') = ["a", "b", "c"]
* StringUtil.split("a..b.c", '.') = ["a", "b", "c"]
* StringUtil.split("a:b:c", '.') = ["a:b:c"]
* StringUtil.split("a b c", ' ') = ["a", "b", "c"]
* </pre>
* <p/>
* </p>
*
* @param str 要分割的字符串
* @param separatorChar 分隔符
* @return 分割后的字符串数组,如果原字符串为<code>null</code>,则返回<code>null</code>
*/
public static String[] split(String str, char separatorChar) {
if (str == null) {
return null;
}
int length = str.length();
if (length == 0) {
return EMPTY_STRING_ARRAY;
}
List<String> list = createLinkedList();
int i = 0;
int start = 0;
boolean match = false;
while (i < length) {
if (str.charAt(i) == separatorChar) {
if (match) {
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
match = true;
i++;
}
if (match) {
list.add(str.substring(start, i));
}
return list.toArray(new String[list.size()]);
}
/**
* 将字符串按指定字符分割。
* <p>
* 分隔符不会出现在目标数组中,连续的分隔符就被看作一个。如果字符串为<code>null</code>,则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.split(null, *) = null
* StringUtil.split("", *) = []
* StringUtil.split("abc def", null) = ["abc", "def"]
* StringUtil.split("abc def", " ") = ["abc", "def"]
* StringUtil.split("abc def", " ") = ["abc", "def"]
* StringUtil.split(" ab: cd::ef ", ":") = ["ab", "cd", "ef"]
* StringUtil.split("abc.def", "") = ["abc.def"]
* </pre>
* <p/>
* </p>
*
* @param str 要分割的字符串
* @param separatorChars 分隔符
* @return 分割后的字符串数组,如果原字符串为<code>null</code>,则返回<code>null</code>
*/
public static String[] split(String str, String separatorChars) {
return split(str, separatorChars, -1);
}
/**
* 将字符串按指定字符分割。
* <p>
* 分隔符不会出现在目标数组中,连续的分隔符就被看作一个。如果字符串为<code>null</code>,则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.split(null, *, *) = null
* StringUtil.split("", *, *) = []
* StringUtil.split("ab cd ef", null, 0) = ["ab", "cd", "ef"]
* StringUtil.split(" ab cd ef ", null, 0) = ["ab", "cd", "ef"]
* StringUtil.split("ab:cd::ef", ":", 0) = ["ab", "cd", "ef"]
* StringUtil.split("ab:cd:ef", ":", 2) = ["ab", "cdef"]
* StringUtil.split("abc.def", "", 2) = ["abc.def"]
* </pre>
* <p/>
* </p>
*
* @param str 要分割的字符串
* @param separatorChars 分隔符
* @param max 返回的数组的最大个数,如果小于等于0,则表示无限制
* @return 分割后的字符串数组,如果原字符串为<code>null</code>,则返回<code>null</code>
*/
public static String[] split(String str, String separatorChars, int max) {
if (str == null) {
return null;
}
int length = str.length();
if (length == 0) {
return EMPTY_STRING_ARRAY;
}
List<String> list = createLinkedList();
int sizePlus1 = 1;
int i = 0;
int start = 0;
boolean match = false;
if (separatorChars == null) {
// null表示使用空白作为分隔符
while (i < length) {
if (Character.isWhitespace(str.charAt(i))) {
if (match) {
if (sizePlus1++ == max) {
i = length;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
match = true;
i++;
}
} else if (separatorChars.length() == 1) {
// 优化分隔符长度为1的情形
char sep = separatorChars.charAt(0);
while (i < length) {
if (str.charAt(i) == sep) {
if (match) {
if (sizePlus1++ == max) {
i = length;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
match = true;
i++;
}
} else {
// 一般情形
while (i < length) {
if (separatorChars.indexOf(str.charAt(i)) >= 0) {
if (match) {
if (sizePlus1++ == max) {
i = length;
}
list.add(str.substring(start, i));
match = false;
}
start = ++i;
continue;
}
match = true;
i++;
}
}
if (match) {
list.add(str.substring(start, i));
}
return list.toArray(new String[list.size()]);
}
// ==========================================================================
// 字符串连接函数。
//
// 将多个对象按指定分隔符连接成字符串。
// ==========================================================================
/**
* 将数组中的元素连接成一个字符串。
* <p/>
* <pre>
* StringUtil.join(null, *) = null
* StringUtil.join([], *) = ""
* StringUtil.join([null], *) = ""
* StringUtil.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtil.join(["a", "b", "c"], null) = "abc"
* StringUtil.join(["a", "b", "c"], "") = "abc"
* StringUtil.join([null, "", "a"], ',') = ",,a"
* </pre>
*
* @param array 要连接的数组
* @param separator 分隔符
* @return 连接后的字符串,如果原数组为<code>null</code>,则返回<code>null</code>
*/
public static String join(Object[] array, String separator) {
if (array == null) {
return null;
}
if (separator == null) {
separator = EMPTY_STRING;
}
int arraySize = array.length;
int bufSize;
if (arraySize == 0) {
bufSize = 0;
} else {
int firstLength = array[0] == null ? 16 : array[0].toString().length();
bufSize = arraySize * (firstLength + separator.length());
}
StringBuilder buf = new StringBuilder(bufSize);
for (int i = 0; i < arraySize; i++) {
if (separator != null && i > 0) {
buf.append(separator);
}
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
/**
* 将<code>Iterator</code>中的元素连接成一个字符串。
* <p/>
* <pre>
* StringUtil.join(null, *) = null
* StringUtil.join([], *) = ""
* StringUtil.join([null], *) = ""
* StringUtil.join(["a", "b", "c"], "--") = "a--b--c"
* StringUtil.join(["a", "b", "c"], null) = "abc"
* StringUtil.join(["a", "b", "c"], "") = "abc"
* StringUtil.join([null, "", "a"], ',') = ",,a"
* </pre>
*
* @param iterator 要连接的<code>Iterator</code>
* @param separator 分隔符
* @return 连接后的字符串,如果原数组为<code>null</code>,则返回<code>null</code>
*/
public static String join(Iterable<?> list, String separator) {
if (list == null) {
return null;
}
StringBuilder buf = new StringBuilder(256); // Java默认值是16, 可能偏小
for (Iterator<?> i = list.iterator(); i.hasNext(); ) {
Object obj = i.next();
if (obj != null) {
buf.append(obj);
}
if (separator != null && i.hasNext()) {
buf.append(separator);
}
}
return buf.toString();
}
// ==========================================================================
// 字符串查找函数 —— 字符或字符串。
// ==========================================================================
/**
* 在字符串中查找指定字符,并返回第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>。
* <p/>
* <pre>
* StringUtil.indexOf(null, *) = -1
* StringUtil.indexOf("", *) = -1
* StringUtil.indexOf("aabaabaa", 'a') = 0
* StringUtil.indexOf("aabaabaa", 'b') = 2
* </pre>
*
* @param str 要扫描的字符串
* @param searchChar 要查找的字符
* @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>
*/
public static int indexOf(String str, char searchChar) {
if (str == null || str.length() == 0) {
return -1;
}
return str.indexOf(searchChar);
}
/**
* 在字符串中查找指定字符,并返回第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>。
* <p/>
* <pre>
* StringUtil.indexOf(null, *, *) = -1
* StringUtil.indexOf("", *, *) = -1
* StringUtil.indexOf("aabaabaa", 'b', 0) = 2
* StringUtil.indexOf("aabaabaa", 'b', 3) = 5
* StringUtil.indexOf("aabaabaa", 'b', 9) = -1
* StringUtil.indexOf("aabaabaa", 'b', -1) = 2
* </pre>
*
* @param str 要扫描的字符串
* @param searchChar 要查找的字符
* @param startPos 开始搜索的索引值,如果小于0,则看作0
* @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>
*/
public static int indexOf(String str, char searchChar, int startPos) {
if (str == null || str.length() == 0) {
return -1;
}
return str.indexOf(searchChar, startPos);
}
/**
* 在字符串中查找指定字符串,并返回第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>。
* <p/>
* <pre>
* StringUtil.indexOf(null, *) = -1
* StringUtil.indexOf(*, null) = -1
* StringUtil.indexOf("", "") = 0
* StringUtil.indexOf("aabaabaa", "a") = 0
* StringUtil.indexOf("aabaabaa", "b") = 2
* StringUtil.indexOf("aabaabaa", "ab") = 1
* StringUtil.indexOf("aabaabaa", "") = 0
* </pre>
*
* @param str 要扫描的字符串
* @param searchStr 要查找的字符串
* @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>
*/
public static int indexOf(String str, String searchStr) {
if (str == null || searchStr == null) {
return -1;
}
return str.indexOf(searchStr);
}
/**
* 在字符串中查找指定字符串,并返回第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>。
* <p/>
* <pre>
* StringUtil.indexOf(null, *, *) = -1
* StringUtil.indexOf(*, null, *) = -1
* StringUtil.indexOf("", "", 0) = 0
* StringUtil.indexOf("aabaabaa", "a", 0) = 0
* StringUtil.indexOf("aabaabaa", "b", 0) = 2
* StringUtil.indexOf("aabaabaa", "ab", 0) = 1
* StringUtil.indexOf("aabaabaa", "b", 3) = 5
* StringUtil.indexOf("aabaabaa", "b", 9) = -1
* StringUtil.indexOf("aabaabaa", "b", -1) = 2
* StringUtil.indexOf("aabaabaa", "", 2) = 2
* StringUtil.indexOf("abc", "", 9) = 3
* </pre>
*
* @param str 要扫描的字符串
* @param searchStr 要查找的字符串
* @param startPos 开始搜索的索引值,如果小于0,则看作0
* @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>
*/
public static int indexOf(String str, String searchStr, int startPos) {
if (str == null || searchStr == null) {
return -1;
}
// JDK1.3及以下版本的bug:不能正确处理下面的情况
if (searchStr.length() == 0 && startPos >= str.length()) {
return str.length();
}
return str.indexOf(searchStr, startPos);
}
/**
* 在字符串中查找指定字符集合中的字符,并返回第一个匹配的起始索引。 如果字符串为<code>null</code>,则返回
* <code>-1</code>。 如果字符集合为<code>null</code>或空,也返回<code>-1</code>。
* <p/>
* <pre>
* StringUtil.indexOfAny(null, *) = -1
* StringUtil.indexOfAny("", *) = -1
* StringUtil.indexOfAny(*, null) = -1
* StringUtil.indexOfAny(*, []) = -1
* StringUtil.indexOfAny("zzabyycdxx",['z','a']) = 0
* StringUtil.indexOfAny("zzabyycdxx",['b','y']) = 3
* StringUtil.indexOfAny("aba", ['z']) = -1
* </pre>
*
* @param str 要扫描的字符串
* @param searchChars 要搜索的字符集合
* @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>
*/
public static int indexOfAny(String str, char[] searchChars) {
if (str == null || str.length() == 0 || searchChars == null || searchChars.length == 0) {
return -1;
}
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
for (char searchChar : searchChars) {
if (searchChar == ch) {
return i;
}
}
}
return -1;
}
/**
* 在字符串中查找指定字符集合中的字符,并返回第一个匹配的起始索引。 如果字符串为<code>null</code>,则返回
* <code>-1</code>。 如果字符集合为<code>null</code>或空,也返回<code>-1</code>。
* <p/>
* <pre>
* StringUtil.indexOfAny(null, *) = -1
* StringUtil.indexOfAny("", *) = -1
* StringUtil.indexOfAny(*, null) = -1
* StringUtil.indexOfAny(*, "") = -1
* StringUtil.indexOfAny("zzabyycdxx", "za") = 0
* StringUtil.indexOfAny("zzabyycdxx", "by") = 3
* StringUtil.indexOfAny("aba","z") = -1
* </pre>
*
* @param str 要扫描的字符串
* @param searchChars 要搜索的字符集合
* @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>
*/
public static int indexOfAny(String str, String searchChars) {
if (str == null || str.length() == 0 || searchChars == null || searchChars.length() == 0) {
return -1;
}
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
for (int j = 0; j < searchChars.length(); j++) {
if (searchChars.charAt(j) == ch) {
return i;
}
}
}
return -1;
}
/**
* 在字符串中查找指定字符串集合中的字符串,并返回第一个匹配的起始索引。 如果字符串为<code>null</code>,则返回
* <code>-1</code>。 如果字符串集合为<code>null</code>或空,也返回<code>-1</code>。
* 如果字符串集合包括<code>""</code>,并且字符串不为<code>null</code>,则返回
* <code>str.length()</code>
* <p/>
* <pre>
* StringUtil.indexOfAny(null, *) = -1
* StringUtil.indexOfAny(*, null) = -1
* StringUtil.indexOfAny(*, []) = -1
* StringUtil.indexOfAny("zzabyycdxx", ["ab","cd"]) = 2
* StringUtil.indexOfAny("zzabyycdxx", ["cd","ab"]) = 2
* StringUtil.indexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtil.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1
* StringUtil.indexOfAny("zzabyycdxx", [""]) = 0
* StringUtil.indexOfAny("", [""]) = 0
* StringUtil.indexOfAny("", ["a"]) = -1
* </pre>
*
* @param str 要扫描的字符串
* @param searchStrs 要搜索的字符串集合
* @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>
*/
public static int indexOfAny(String str, String[] searchStrs) {
if (str == null || searchStrs == null) {
return -1;
}
int sz = searchStrs.length;
// String's can't have a MAX_VALUEth index.
int ret = Integer.MAX_VALUE;
int tmp = 0;
for (int i = 0; i < sz; i++) {
String search = searchStrs[i];
if (search == null) {
continue;
}
tmp = str.indexOf(search);
if (tmp == -1) {
continue;
}
if (tmp < ret) {
ret = tmp;
}
}
return ret == Integer.MAX_VALUE ? -1 : ret;
}
/**
* 在字符串中查找不在指定字符集合中的字符,并返回第一个匹配的起始索引。 如果字符串为<code>null</code>,则返回
* <code>-1</code>。 如果字符集合为<code>null</code>或空,也返回<code>-1</code>。
* <p/>
* <pre>
* StringUtil.indexOfAnyBut(null, *) = -1
* StringUtil.indexOfAnyBut("", *) = -1
* StringUtil.indexOfAnyBut(*, null) = -1
* StringUtil.indexOfAnyBut(*, []) = -1
* StringUtil.indexOfAnyBut("zzabyycdxx",'za') = 3
* StringUtil.indexOfAnyBut("zzabyycdxx", 'by') = 0
* StringUtil.indexOfAnyBut("aba", 'ab') = -1
* </pre>
*
* @param str 要扫描的字符串
* @param searchChars 要搜索的字符集合
* @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>
*/
public static int indexOfAnyBut(String str, char[] searchChars) {
if (str == null || str.length() == 0 || searchChars == null || searchChars.length == 0) {
return -1;
}
outer:
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
for (int j = 0; j < searchChars.length; j++) {
if (searchChars[j] == ch) {
continue outer;
}
}
return i;
}
return -1;
}
/**
* 在字符串中查找不在指定字符集合中的字符,并返回第一个匹配的起始索引。 如果字符串为<code>null</code>,则返回
* <code>-1</code>。 如果字符集合为<code>null</code>或空,也返回<code>-1</code>。
* <p/>
* <pre>
* StringUtil.indexOfAnyBut(null, *) = -1
* StringUtil.indexOfAnyBut("", *) = -1
* StringUtil.indexOfAnyBut(*, null) = -1
* StringUtil.indexOfAnyBut(*, "") = -1
* StringUtil.indexOfAnyBut("zzabyycdxx", "za") = 3
* StringUtil.indexOfAnyBut("zzabyycdxx", "by") = 0
* StringUtil.indexOfAnyBut("aba","ab") = -1
* </pre>
*
* @param str 要扫描的字符串
* @param searchChars 要搜索的字符集合
* @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>
*/
public static int indexOfAnyBut(String str, String searchChars) {
if (str == null || str.length() == 0 || searchChars == null || searchChars.length() == 0) {
return -1;
}
for (int i = 0; i < str.length(); i++) {
if (searchChars.indexOf(str.charAt(i)) < 0) {
return i;
}
}
return -1;
}
/**
* 从字符串尾部开始查找指定字符,并返回第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回
* <code>-1</code>。
* <p/>
* <pre>
* StringUtil.lastIndexOf(null, *) = -1
* StringUtil.lastIndexOf("", *) = -1
* StringUtil.lastIndexOf("aabaabaa", 'a') = 7
* StringUtil.lastIndexOf("aabaabaa", 'b') = 5
* </pre>
*
* @param str 要扫描的字符串
* @param searchChar 要查找的字符
* @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>
*/
public static int lastIndexOf(String str, char searchChar) {
if (str == null || str.length() == 0) {
return -1;
}
return str.lastIndexOf(searchChar);
}
/**
* 从字符串尾部开始查找指定字符,并返回第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回
* <code>-1</code>。
* <p/>
* <pre>
* StringUtil.lastIndexOf(null, *, *) = -1
* StringUtil.lastIndexOf("", *, *) = -1
* StringUtil.lastIndexOf("aabaabaa", 'b', 8) = 5
* StringUtil.lastIndexOf("aabaabaa", 'b', 4) = 2
* StringUtil.lastIndexOf("aabaabaa", 'b', 0) = -1
* StringUtil.lastIndexOf("aabaabaa", 'b', 9) = 5
* StringUtil.lastIndexOf("aabaabaa", 'b', -1) = -1
* StringUtil.lastIndexOf("aabaabaa", 'a', 0) = 0
* </pre>
*
* @param str 要扫描的字符串
* @param searchChar 要查找的字符
* @param startPos 从指定索引开始向前搜索
* @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>
*/
public static int lastIndexOf(String str, char searchChar, int startPos) {
if (str == null || str.length() == 0) {
return -1;
}
return str.lastIndexOf(searchChar, startPos);
}
/**
* 从字符串尾部开始查找指定字符串,并返回第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回
* <code>-1</code>。
* <p/>
* <pre>
* StringUtil.lastIndexOf(null, *) = -1
* StringUtil.lastIndexOf("", *) = -1
* StringUtil.lastIndexOf("aabaabaa", 'a') = 7
* StringUtil.lastIndexOf("aabaabaa", 'b') = 5
* </pre>
*
* @param str 要扫描的字符串
* @param searchStr 要查找的字符串
* @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>
*/
public static int lastIndexOf(String str, String searchStr) {
if (str == null || searchStr == null) {
return -1;
}
return str.lastIndexOf(searchStr);
}
/**
* 从字符串尾部开始查找指定字符串,并返回第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回
* <code>-1</code>。
* <p/>
* <pre>
* StringUtil.lastIndexOf(null, *, *) = -1
* StringUtil.lastIndexOf(*, null, *) = -1
* StringUtil.lastIndexOf("aabaabaa", "a", 8) = 7
* StringUtil.lastIndexOf("aabaabaa", "b", 8) = 5
* StringUtil.lastIndexOf("aabaabaa", "ab", 8) = 4
* StringUtil.lastIndexOf("aabaabaa", "b", 9) = 5
* StringUtil.lastIndexOf("aabaabaa", "b", -1) = -1
* StringUtil.lastIndexOf("aabaabaa", "a", 0) = 0
* StringUtil.lastIndexOf("aabaabaa", "b", 0) = -1
* </pre>
*
* @param str 要扫描的字符串
* @param searchStr 要查找的字符串
* @param startPos 从指定索引开始向前搜索
* @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>
*/
public static int lastIndexOf(String str, String searchStr, int startPos) {
if (str == null || searchStr == null) {
return -1;
}
return str.lastIndexOf(searchStr, startPos);
}
/**
* 从字符串尾部开始查找指定字符串集合中的字符串,并返回第一个匹配的起始索引。 如果字符串为<code>null</code>,则返回
* <code>-1</code>。 如果字符串集合为<code>null</code>或空,也返回<code>-1</code>。
* 如果字符串集合包括<code>""</code>,并且字符串不为<code>null</code>,则返回
* <code>str.length()</code>
* <p/>
* <pre>
* StringUtil.lastIndexOfAny(null, *) = -1
* StringUtil.lastIndexOfAny(*, null) = -1
* StringUtil.lastIndexOfAny(*, []) = -1
* StringUtil.lastIndexOfAny(*, [null]) = -1
* StringUtil.lastIndexOfAny("zzabyycdxx", ["ab","cd"]) = 6
* StringUtil.lastIndexOfAny("zzabyycdxx", ["cd","ab"]) = 6
* StringUtil.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtil.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
* StringUtil.lastIndexOfAny("zzabyycdxx", ["mn",""]) = 10
* </pre>
*
* @param str 要扫描的字符串
* @param searchStrs 要搜索的字符串集合
* @return 第一个匹配的索引值。如果字符串为<code>null</code>或未找到,则返回<code>-1</code>
*/
public static int lastIndexOfAny(String str, String[] searchStrs) {
if (str == null || searchStrs == null) {
return -1;
}
int searchStrsLength = searchStrs.length;
int index = -1;
int tmp = 0;
for (int i = 0; i < searchStrsLength; i++) {
String search = searchStrs[i];
if (search == null) {
continue;
}
tmp = str.lastIndexOf(search);
if (tmp > index) {
index = tmp;
}
}
return index;
}
/**
* 检查字符串中是否包含指定的字符。如果字符串为<code>null</code>,将返回<code>false</code>。
* <p/>
* <pre>
* StringUtil.contains(null, *) = false
* StringUtil.contains("", *) = false
* StringUtil.contains("abc", 'a') = true
* StringUtil.contains("abc", 'z') = false
* </pre>
*
* @param str 要扫描的字符串
* @param searchChar 要查找的字符
* @return 如果找到,则返回<code>true</code>
*/
public static boolean contains(String str, char searchChar) {
if (str == null || str.length() == 0) {
return false;
}
return str.indexOf(searchChar) >= 0;
}
/**
* 检查字符串中是否包含指定的字符串。如果字符串为<code>null</code>,将返回<code>false</code>。
* <p/>
* <pre>
* StringUtil.contains(null, *) = false
* StringUtil.contains(*, null) = false
* StringUtil.contains("", "") = true
* StringUtil.contains("abc", "") = true
* StringUtil.contains("abc", "a") = true
* StringUtil.contains("abc", "z") = false
* </pre>
*
* @param str 要扫描的字符串
* @param searchStr 要查找的字符串
* @return 如果找到,则返回<code>true</code>
*/
public static boolean contains(String str, String searchStr) {
if (str == null || searchStr == null) {
return false;
}
return str.indexOf(searchStr) >= 0;
}
/**
* 检查字符串是是否只包含指定字符集合中的字符。
* <p>
* 如果字符串为<code>null</code>,则返回<code>false</code>。 如果字符集合为<code>null</code>
* 则返回<code>false</code>。 但是空字符串永远返回<code>true</code>.
* </p>
* <p/>
* <pre>
* StringUtil.containsOnly(null, *) = false
* StringUtil.containsOnly(*, null) = false
* StringUtil.containsOnly("", *) = true
* StringUtil.containsOnly("ab", '') = false
* StringUtil.containsOnly("abab", 'abc') = true
* StringUtil.containsOnly("ab1", 'abc') = false
* StringUtil.containsOnly("abz", 'abc') = false
* </pre>
*
* @param str 要扫描的字符串
* @param valid 要查找的字符串
* @return 如果找到,则返回<code>true</code>
*/
public static boolean containsOnly(String str, char[] valid) {
if (valid == null || str == null) {
return false;
}
if (str.length() == 0) {
return true;
}
if (valid.length == 0) {
return false;
}
return indexOfAnyBut(str, valid) == -1;
}
/**
* 检查字符串是是否只包含指定字符集合中的字符。
* <p>
* 如果字符串为<code>null</code>,则返回<code>false</code>。 如果字符集合为<code>null</code>
* 则返回<code>false</code>。 但是空字符串永远返回<code>true</code>.
* </p>
* <p/>
* <pre>
* StringUtil.containsOnly(null, *) = false
* StringUtil.containsOnly(*, null) = false
* StringUtil.containsOnly("", *) = true
* StringUtil.containsOnly("ab", "") = false
* StringUtil.containsOnly("abab", "abc") = true
* StringUtil.containsOnly("ab1", "abc") = false
* StringUtil.containsOnly("abz", "abc") = false
* </pre>
*
* @param str 要扫描的字符串
* @param valid 要查找的字符串
* @return 如果找到,则返回<code>true</code>
*/
public static boolean containsOnly(String str, String valid) {
if (str == null || valid == null) {
return false;
}
return containsOnly(str, valid.toCharArray());
}
/**
* 检查字符串是是否不包含指定字符集合中的字符。
* <p>
* 如果字符串为<code>null</code>,则返回<code>false</code>。 如果字符集合为<code>null</code>
* 则返回<code>true</code>。 但是空字符串永远返回<code>true</code>.
* </p>
* <p/>
* <pre>
* StringUtil.containsNone(null, *) = true
* StringUtil.containsNone(*, null) = true
* StringUtil.containsNone("", *) = true
* StringUtil.containsNone("ab", '') = true
* StringUtil.containsNone("abab", 'xyz') = true
* StringUtil.containsNone("ab1", 'xyz') = true
* StringUtil.containsNone("abz", 'xyz') = false
* </pre>
*
* @param str 要扫描的字符串
* @param invalid 要查找的字符串
* @return 如果找到,则返回<code>true</code>
*/
public static boolean containsNone(String str, char[] invalid) {
if (str == null || invalid == null) {
return true;
}
int strSize = str.length();
int validSize = invalid.length;
for (int i = 0; i < strSize; i++) {
char ch = str.charAt(i);
for (int j = 0; j < validSize; j++) {
if (invalid[j] == ch) {
return false;
}
}
}
return true;
}
/**
* 检查字符串是是否不包含指定字符集合中的字符。
* <p>
* 如果字符串为<code>null</code>,则返回<code>false</code>。 如果字符集合为<code>null</code>
* 则返回<code>true</code>。 但是空字符串永远返回<code>true</code>.
* </p>
* <p/>
* <pre>
* StringUtil.containsNone(null, *) = true
* StringUtil.containsNone(*, null) = true
* StringUtil.containsNone("", *) = true
* StringUtil.containsNone("ab", "") = true
* StringUtil.containsNone("abab", "xyz") = true
* StringUtil.containsNone("ab1", "xyz") = true
* StringUtil.containsNone("abz", "xyz") = false
* </pre>
*
* @param str 要扫描的字符串
* @param invalidChars 要查找的字符串
* @return 如果找到,则返回<code>true</code>
*/
public static boolean containsNone(String str, String invalidChars) {
if (str == null || invalidChars == null) {
return true;
}
return containsNone(str, invalidChars.toCharArray());
}
/**
* 取得指定子串在字符串中出现的次数。
* <p>
* 如果字符串为<code>null</code>或空,则返回<code>0</code>。
* <p/>
* <pre>
* StringUtil.countMatches(null, *) = 0
* StringUtil.countMatches("", *) = 0
* StringUtil.countMatches("abba", null) = 0
* StringUtil.countMatches("abba", "") = 0
* StringUtil.countMatches("abba", "a") = 2
* StringUtil.countMatches("abba", "ab") = 1
* StringUtil.countMatches("abba", "xxx") = 0
* </pre>
* <p/>
* </p>
*
* @param str 要扫描的字符串
* @param subStr 子字符串
* @return 子串在字符串中出现的次数,如果字符串为<code>null</code>或空,则返回<code>0</code>
*/
public static int countMatches(String str, String subStr) {
if (str == null || str.length() == 0 || subStr == null || subStr.length() == 0) {
return 0;
}
int count = 0;
int index = 0;
while ((index = str.indexOf(subStr, index)) != -1) {
count++;
index += subStr.length();
}
return count;
}
// ==========================================================================
// 取子串函数。
// ==========================================================================
/**
* 取指定字符串的子串。
* <p>
* 负的索引代表从尾部开始计算。如果字符串为<code>null</code>,则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.substring(null, *) = null
* StringUtil.substring("", *) = ""
* StringUtil.substring("abc", 0) = "abc"
* StringUtil.substring("abc", 2) = "c"
* StringUtil.substring("abc", 4) = ""
* StringUtil.substring("abc", -2) = "bc"
* StringUtil.substring("abc", -4) = "abc"
* </pre>
* <p/>
* </p>
*
* @param str 字符串
* @param start 起始索引,如果为负数,表示从尾部查找
* @return 子串,如果原始串为<code>null</code>,则返回<code>null</code>
*/
public static String substring(String str, int start) {
if (str == null) {
return null;
}
if (start < 0) {
start = str.length() + start;
}
if (start < 0) {
start = 0;
}
if (start > str.length()) {
return EMPTY_STRING;
}
return str.substring(start);
}
/**
* 取指定字符串的子串。
* <p>
* 负的索引代表从尾部开始计算。如果字符串为<code>null</code>,则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.substring(null, *, *) = null
* StringUtil.substring("", * , *) = "";
* StringUtil.substring("abc", 0, 2) = "ab"
* StringUtil.substring("abc", 2, 0) = ""
* StringUtil.substring("abc", 2, 4) = "c"
* StringUtil.substring("abc", 4, 6) = ""
* StringUtil.substring("abc", 2, 2) = ""
* StringUtil.substring("abc", -2, -1) = "b"
* StringUtil.substring("abc", -4, 2) = "ab"
* </pre>
* <p/>
* </p>
*
* @param str 字符串
* @param start 起始索引,如果为负数,表示从尾部计算
* @param end 结束索引(不含),如果为负数,表示从尾部计算
* @return 子串,如果原始串为<code>null</code>,则返回<code>null</code>
*/
public static String substring(String str, int start, int end) {
if (str == null) {
return null;
}
if (end < 0) {
end = str.length() + end;
}
if (start < 0) {
start = str.length() + start;
}
if (end > str.length()) {
end = str.length();
}
if (start > end) {
return EMPTY_STRING;
}
if (start < 0) {
start = 0;
}
if (end < 0) {
end = 0;
}
return str.substring(start, end);
}
/**
* 取得长度为指定字符数的最左边的子串。
* <p/>
* <pre>
* StringUtil.left(null, *) = null
* StringUtil.left(*, -ve) = ""
* StringUtil.left("", *) = ""
* StringUtil.left("abc", 0) = ""
* StringUtil.left("abc", 2) = "ab"
* StringUtil.left("abc", 4) = "abc"
* </pre>
*
* @param str 字符串
* @param len 最左子串的长度
* @return 子串,如果原始字串为<code>null</code>,则返回<code>null</code>
*/
public static String left(String str, int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY_STRING;
}
if (str.length() <= len) {
return str;
} else {
return str.substring(0, len);
}
}
/**
* 取得长度为指定字符数的最右边的子串。
* <p/>
* <pre>
* StringUtil.right(null, *) = null
* StringUtil.right(*, -ve) = ""
* StringUtil.right("", *) = ""
* StringUtil.right("abc", 0) = ""
* StringUtil.right("abc", 2) = "bc"
* StringUtil.right("abc", 4) = "abc"
* </pre>
*
* @param str 字符串
* @param len 最右子串的长度
* @return 子串,如果原始字串为<code>null</code>,则返回<code>null</code>
*/
public static String right(String str, int len) {
if (str == null) {
return null;
}
if (len < 0) {
return EMPTY_STRING;
}
if (str.length() <= len) {
return str;
} else {
return str.substring(str.length() - len);
}
}
/**
* 取得从指定索引开始计算的、长度为指定字符数的子串。
* <p/>
* <pre>
* StringUtil.mid(null, *, *) = null
* StringUtil.mid(*, *, -ve) = ""
* StringUtil.mid("", 0, *) = ""
* StringUtil.mid("abc", 0, 2) = "ab"
* StringUtil.mid("abc", 0, 4) = "abc"
* StringUtil.mid("abc", 2, 4) = "c"
* StringUtil.mid("abc", 4, 2) = ""
* StringUtil.mid("abc", -2, 2) = "ab"
* </pre>
*
* @param str 字符串
* @param pos 起始索引,如果为负数,则看作<code>0</code>
* @param len 子串的长度,如果为负数,则看作长度为<code>0</code>
* @return 子串,如果原始字串为<code>null</code>,则返回<code>null</code>
*/
public static String mid(String str, int pos, int len) {
if (str == null) {
return null;
}
if (len < 0 || pos > str.length()) {
return EMPTY_STRING;
}
if (pos < 0) {
pos = 0;
}
if (str.length() <= pos + len) {
return str.substring(pos);
} else {
return str.substring(pos, pos + len);
}
}
// ==========================================================================
// 搜索并取子串函数。
// ==========================================================================
/**
* 取得第一个出现的分隔子串之前的子串。
* <p>
* 如果字符串为<code>null</code>,则返回<code>null</code>。 如果分隔子串为<code>null</code>
* 或未找到该子串,则返回原字符串。
* <p/>
* <pre>
* StringUtil.substringBefore(null, *) = null
* StringUtil.substringBefore("", *) = ""
* StringUtil.substringBefore("abc", "a") = ""
* StringUtil.substringBefore("abcba", "b") = "a"
* StringUtil.substringBefore("abc", "c") = "ab"
* StringUtil.substringBefore("abc", "d") = "abc"
* StringUtil.substringBefore("abc", "") = ""
* StringUtil.substringBefore("abc", null) = "abc"
* </pre>
* <p/>
* </p>
*
* @param str 字符串
* @param separator 要搜索的分隔子串
* @return 子串,如果原始串为<code>null</code>,则返回<code>null</code>
*/
public static String substringBefore(String str, String separator) {
if (str == null || separator == null || str.length() == 0) {
return str;
}
if (separator.length() == 0) {
return EMPTY_STRING;
}
int pos = str.indexOf(separator);
if (pos == -1) {
return str;
}
return str.substring(0, pos);
}
/**
* 取得第一个出现的分隔子串之后的子串。
* <p>
* 如果字符串为<code>null</code>,则返回<code>null</code>。 如果分隔子串为<code>null</code>
* 或未找到该子串,则返回原字符串。
* <p/>
* <pre>
* StringUtil.substringAfter(null, *) = null
* StringUtil.substringAfter("", *) = ""
* StringUtil.substringAfter(*, null) = ""
* StringUtil.substringAfter("abc", "a") = "bc"
* StringUtil.substringAfter("abcba", "b") = "cba"
* StringUtil.substringAfter("abc", "c") = ""
* StringUtil.substringAfter("abc", "d") = ""
* StringUtil.substringAfter("abc", "") = "abc"
* </pre>
* <p/>
* </p>
*
* @param str 字符串
* @param separator 要搜索的分隔子串
* @return 子串,如果原始串为<code>null</code>,则返回<code>null</code>
*/
public static String substringAfter(String str, String separator) {
if (str == null || str.length() == 0) {
return str;
}
if (separator == null) {
return EMPTY_STRING;
}
int pos = str.indexOf(separator);
if (pos == -1) {
return EMPTY_STRING;
}
return str.substring(pos + separator.length());
}
/**
* 取得最后一个的分隔子串之前的子串。
* <p>
* 如果字符串为<code>null</code>,则返回<code>null</code>。 如果分隔子串为<code>null</code>
* 或未找到该子串,则返回原字符串。
* <p/>
* <pre>
* StringUtil.substringBeforeLast(null, *) = null
* StringUtil.substringBeforeLast("", *) = ""
* StringUtil.substringBeforeLast("abcba", "b") = "abc"
* StringUtil.substringBeforeLast("abc", "c") = "ab"
* StringUtil.substringBeforeLast("a", "a") = ""
* StringUtil.substringBeforeLast("a", "z") = "a"
* StringUtil.substringBeforeLast("a", null) = "a"
* StringUtil.substringBeforeLast("a", "") = "a"
* </pre>
* <p/>
* </p>
*
* @param str 字符串
* @param separator 要搜索的分隔子串
* @return 子串,如果原始串为<code>null</code>,则返回<code>null</code>
*/
public static String substringBeforeLast(String str, String separator) {
if (str == null || separator == null || str.length() == 0 || separator.length() == 0) {
return str;
}
int pos = str.lastIndexOf(separator);
if (pos == -1) {
return str;
}
return str.substring(0, pos);
}
/**
* 取得最后一个的分隔子串之后的子串。
* <p>
* 如果字符串为<code>null</code>,则返回<code>null</code>。 如果分隔子串为<code>null</code>
* 或未找到该子串,则返回原字符串。
* <p/>
* <pre>
* StringUtil.substringAfterLast(null, *) = null
* StringUtil.substringAfterLast("", *) = ""
* StringUtil.substringAfterLast(*, "") = ""
* StringUtil.substringAfterLast(*, null) = ""
* StringUtil.substringAfterLast("abc", "a") = "bc"
* StringUtil.substringAfterLast("abcba", "b") = "a"
* StringUtil.substringAfterLast("abc", "c") = ""
* StringUtil.substringAfterLast("a", "a") = ""
* StringUtil.substringAfterLast("a", "z") = ""
* </pre>
* <p/>
* </p>
*
* @param str 字符串
* @param separator 要搜索的分隔子串
* @return 子串,如果原始串为<code>null</code>,则返回<code>null</code>
*/
public static String substringAfterLast(String str, String separator) {
if (str == null || str.length() == 0) {
return str;
}
if (separator == null || separator.length() == 0) {
return EMPTY_STRING;
}
int pos = str.lastIndexOf(separator);
if (pos == -1 || pos == str.length() - separator.length()) {
return EMPTY_STRING;
}
return str.substring(pos + separator.length());
}
/**
* 取得指定分隔符的前两次出现之间的子串。
* <p>
* 如果字符串为<code>null</code>,则返回<code>null</code>。 如果分隔子串为<code>null</code>
* ,则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.substringBetween(null, *) = null
* StringUtil.substringBetween("", "") = ""
* StringUtil.substringBetween("", "tag") = null
* StringUtil.substringBetween("tagabctag", null) = null
* StringUtil.substringBetween("tagabctag", "") = ""
* StringUtil.substringBetween("tagabctag", "tag") = "abc"
* </pre>
* <p/>
* </p>
*
* @param str 字符串
* @param tag 要搜索的分隔子串
* @return 子串,如果原始串为<code>null</code>或未找到分隔子串,则返回<code>null</code>
*/
public static String substringBetween(String str, String tag) {
return substringBetween(str, tag, tag, 0);
}
/**
* 取得两个分隔符之间的子串。
* <p>
* 如果字符串为<code>null</code>,则返回<code>null</code>。 如果分隔子串为<code>null</code>
* ,则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.substringBetween(null, *, *) = null
* StringUtil.substringBetween("", "", "") = ""
* StringUtil.substringBetween("", "", "tag") = null
* StringUtil.substringBetween("", "tag", "tag") = null
* StringUtil.substringBetween("yabcz", null, null) = null
* StringUtil.substringBetween("yabcz", "", "") = ""
* StringUtil.substringBetween("yabcz", "y", "z") = "abc"
* StringUtil.substringBetween("yabczyabcz", "y", "z") = "abc"
* </pre>
* <p/>
* </p>
*
* @param str 字符串
* @param open 要搜索的分隔子串1
* @param close 要搜索的分隔子串2
* @return 子串,如果原始串为<code>null</code>或未找到分隔子串,则返回<code>null</code>
*/
public static String substringBetween(String str, String open, String close) {
return substringBetween(str, open, close, 0);
}
/**
* 取得两个分隔符之间的子串。
* <p>
* 如果字符串为<code>null</code>,则返回<code>null</code>。 如果分隔子串为<code>null</code>
* ,则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.substringBetween(null, *, *) = null
* StringUtil.substringBetween("", "", "") = ""
* StringUtil.substringBetween("", "", "tag") = null
* StringUtil.substringBetween("", "tag", "tag") = null
* StringUtil.substringBetween("yabcz", null, null) = null
* StringUtil.substringBetween("yabcz", "", "") = ""
* StringUtil.substringBetween("yabcz", "y", "z") = "abc"
* StringUtil.substringBetween("yabczyabcz", "y", "z") = "abc"
* </pre>
* <p/>
* </p>
*
* @param str 字符串
* @param open 要搜索的分隔子串1
* @param close 要搜索的分隔子串2
* @param fromIndex 从指定index处搜索
* @return 子串,如果原始串为<code>null</code>或未找到分隔子串,则返回<code>null</code>
*/
public static String substringBetween(String str, String open, String close, int fromIndex) {
if (str == null || open == null || close == null) {
return null;
}
int start = str.indexOf(open, fromIndex);
if (start != -1) {
int end = str.indexOf(close, start + open.length());
if (end != -1) {
return str.substring(start + open.length(), end);
}
}
return null;
}
// ==========================================================================
// 删除字符。
// ==========================================================================
/**
* 删除所有在<code>Character.isWhitespace(char)</code>中所定义的空白。
* <p/>
* <pre>
* StringUtil.deleteWhitespace(null) = null
* StringUtil.deleteWhitespace("") = ""
* StringUtil.deleteWhitespace("abc") = "abc"
* StringUtil.deleteWhitespace(" ab c ") = "abc"
* </pre>
*
* @param str 要处理的字符串
* @return 去空白后的字符串,如果原始字符串为<code>null</code>,则返回<code>null</code>
*/
public static String deleteWhitespace(String str) {
if (str == null) {
return null;
}
int sz = str.length();
StringBuilder buffer = new StringBuilder(sz);
for (int i = 0; i < sz; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
buffer.append(str.charAt(i));
}
}
return buffer.toString();
}
// ==========================================================================
// 替换子串。
// ==========================================================================
/**
* 替换指定的子串,替换所有出现的子串。
* <p>
* 如果字符串为<code>null</code>则返回<code>null</code>,如果指定子串为<code>null</code>
* ,则返回原字符串。
* <p/>
* <pre>
* StringUtil.replace(null, *, *) = null
* StringUtil.replace("", *, *) = ""
* StringUtil.replace("aba", null, null) = "aba"
* StringUtil.replace("aba", null, null) = "aba"
* StringUtil.replace("aba", "a", null) = "aba"
* StringUtil.replace("aba", "a", "") = "b"
* StringUtil.replace("aba", "a", "z") = "zbz"
* </pre>
* <p/>
* </p>
*
* @param text 要扫描的字符串
* @param repl 要搜索的子串
* @param with 替换字符串
* @return 被替换后的字符串,如果原始字符串为<code>null</code>,则返回<code>null</code>
*/
public static String replace(String text, String repl, String with) {
return replace(text, repl, with, -1);
}
/**
* 替换指定的子串,替换指定的次数。
* <p>
* 如果字符串为<code>null</code>则返回<code>null</code>,如果指定子串为<code>null</code>
* ,则返回原字符串。
* <p/>
* <pre>
* StringUtil.replace(null, *, *, *) = null
* StringUtil.replace("", *, *, *) = ""
* StringUtil.replace("abaa", null, null, 1) = "abaa"
* StringUtil.replace("abaa", null, null, 1) = "abaa"
* StringUtil.replace("abaa", "a", null, 1) = "abaa"
* StringUtil.replace("abaa", "a", "", 1) = "baa"
* StringUtil.replace("abaa", "a", "z", 0) = "abaa"
* StringUtil.replace("abaa", "a", "z", 1) = "zbaa"
* StringUtil.replace("abaa", "a", "z", 2) = "zbza"
* StringUtil.replace("abaa", "a", "z", -1) = "zbzz"
* </pre>
* <p/>
* </p>
*
* @param text 要扫描的字符串
* @param repl 要搜索的子串
* @param with 替换字符串
* @param max maximum number of values to replace, or <code>-1</code> if no
* maximum
* @return 被替换后的字符串,如果原始字符串为<code>null</code>,则返回<code>null</code>
*/
public static String replace(String text, String repl, String with, int max) {
if (text == null || repl == null || with == null || repl.length() == 0 || max == 0) {
return text;
}
StringBuilder buf = new StringBuilder(text.length());
int start = 0;
int end = 0;
while ((end = text.indexOf(repl, start)) != -1) {
buf.append(text.substring(start, end)).append(with);
start = end + repl.length();
if (--max == 0) {
break;
}
}
buf.append(text.substring(start));
return buf.toString();
}
/**
* 将字符串中所有指定的字符,替换成另一个。
* <p>
* 如果字符串为<code>null</code>则返回<code>null</code>。
* <p/>
* <pre>
* StringUtil.replaceChars(null, *, *) = null
* StringUtil.replaceChars("", *, *) = ""
* StringUtil.replaceChars("abcba", 'b', 'y') = "aycya"
* StringUtil.replaceChars("abcba", 'z', 'y') = "abcba"
* </pre>
* <p/>
* </p>
*
* @param str 要扫描的字符串
* @param searchChar 要搜索的字符
* @param replaceChar 替换字符
* @return 被替换后的字符串,如果原始字符串为<code>null</code>,则返回<code>null</code>
*/
public static String replaceChar(String str, char searchChar, char replaceChar) {
if (str == null) {
return null;
}
return str.replace(searchChar, replaceChar);
}
/**
* 将字符串中所有指定的字符,替换成另一个。
* <p>
* 如果字符串为<code>null</code>则返回<code>null</code>。如果搜索字符串为<code>null</code>
* 或空,则返回原字符串。
* </p>
* <p>
* 例如:
* <code>replaceChars("hello", "ho", "jy") = jelly</code>
* 。
* </p>
* <p>
* 通常搜索字符串和替换字符串是等长的,如果搜索字符串比替换字符串长,则多余的字符将被删除。 如果搜索字符串比替换字符串短,则缺少的字符将被忽略。
* <p/>
* <pre>
* StringUtil.replaceChars(null, *, *) = null
* StringUtil.replaceChars("", *, *) = ""
* StringUtil.replaceChars("abc", null, *) = "abc"
* StringUtil.replaceChars("abc", "", *) = "abc"
* StringUtil.replaceChars("abc", "b", null) = "ac"
* StringUtil.replaceChars("abc", "b", "") = "ac"
* StringUtil.replaceChars("abcba", "bc", "yz") = "ayzya"
* StringUtil.replaceChars("abcba", "bc", "y") = "ayya"
* StringUtil.replaceChars("abcba", "bc", "yzx") = "ayzya"
* </pre>
* <p/>
* </p>
*
* @param str 要扫描的字符串
* @param searchChars 要搜索的字符串
* @param replaceChars 替换字符串
* @return 被替换后的字符串,如果原始字符串为<code>null</code>,则返回<code>null</code>
*/
public static String replaceChars(String str, String searchChars, String replaceChars) {
if (str == null || str.length() == 0 || searchChars == null || searchChars.length() == 0) {
return str;
}
char[] chars = str.toCharArray();
int len = chars.length;
boolean modified = false;
for (int i = 0, isize = searchChars.length(); i < isize; i++) {
char searchChar = searchChars.charAt(i);
if (replaceChars == null || i >= replaceChars.length()) {
// 删除
int pos = 0;
for (int j = 0; j < len; j++) {
if (chars[j] != searchChar) {
chars[pos++] = chars[j];
} else {
modified = true;
}
}
len = pos;
} else {
// 替换
for (int j = 0; j < len; j++) {
if (chars[j] == searchChar) {
chars[j] = replaceChars.charAt(i);
modified = true;
}
}
}
}
if (!modified) {
return str;
}
return new String(chars, 0, len);
}
/**
* 将指定的子串用另一指定子串覆盖。
* <p>
* 如果字符串为<code>null</code>,则返回<code>null</code>。 负的索引值将被看作<code>0</code>
* ,越界的索引值将被设置成字符串的长度相同的值。
* <p/>
* <pre>
* StringUtil.overlay(null, *, *, *) = null
* StringUtil.overlay("", "abc", 0, 0) = "abc"
* StringUtil.overlay("abcdef", null, 2, 4) = "abef"
* StringUtil.overlay("abcdef", "", 2, 4) = "abef"
* StringUtil.overlay("abcdef", "", 4, 2) = "abef"
* StringUtil.overlay("abcdef", "zzzz", 2, 4) = "abzzzzef"
* StringUtil.overlay("abcdef", "zzzz", 4, 2) = "abzzzzef"
* StringUtil.overlay("abcdef", "zzzz", -1, 4) = "zzzzef"
* StringUtil.overlay("abcdef", "zzzz", 2, 8) = "abzzzz"
* StringUtil.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
* StringUtil.overlay("abcdef", "zzzz", 8, 10) = "abcdefzzzz"
* </pre>
* <p/>
* </p>
*
* @param str 要扫描的字符串
* @param overlay 用来覆盖的字符串
* @param start 起始索引
* @param end 结束索引
* @return 被覆盖后的字符串,如果原始字符串为<code>null</code>,则返回<code>null</code>
*/
public static String overlay(String str, String overlay, int start, int end) {
if (str == null) {
return null;
}
if (overlay == null) {
overlay = EMPTY_STRING;
}
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 StringBuilder(len + start - end + overlay.length() + 1).append(str.substring(0, start))
.append(overlay).append(str.substring(end)).toString();
}
// ==========================================================================
// 重复字符串。
// ==========================================================================
/**
* 将指定字符串重复n遍。
* <p/>
* <pre>
* StringUtil.repeat(null, 2) = null
* StringUtil.repeat("", 0) = ""
* StringUtil.repeat("", 2) = ""
* StringUtil.repeat("a", 3) = "aaa"
* StringUtil.repeat("ab", 2) = "abab"
* StringUtil.repeat("abcd", 2) = "abcdabcd"
* StringUtil.repeat("a", -2) = ""
* </pre>
*
* @param str 要重复的字符串
* @param repeat 重复次数,如果小于<code>0</code>,则看作<code>0</code>
* @return 重复n次的字符串,如果原始字符串为<code>null</code>,则返回<code>null</code>
*/
public static String repeat(String str, int repeat) {
if (str == null) {
return null;
}
if (repeat <= 0) {
return EMPTY_STRING;
}
int inputLength = str.length();
if (repeat == 1 || inputLength == 0) {
return str;
}
int outputLength = inputLength * repeat;
switch (inputLength) {
case 1:
char ch = str.charAt(0);
char[] output1 = new char[outputLength];
for (int i = repeat - 1; i >= 0; i--) {
output1[i] = ch;
}
return new String(output1);
case 2:
char ch0 = str.charAt(0);
char ch1 = str.charAt(1);
char[] output2 = new char[outputLength];
for (int i = repeat * 2 - 2; i >= 0; i--, i--) {
output2[i] = ch0;
output2[i + 1] = ch1;
}
return new String(output2);
default:
StringBuilder buf = new StringBuilder(outputLength);
for (int i = 0; i < repeat; i++) {
buf.append(str);
}
return buf.toString();
}
}
// ==========================================================================
// Perl风格的chomp和chop函数。
// ==========================================================================
/**
* 删除字符串末尾的换行符。如果字符串不以换行结尾,则什么也不做。
* <p>
* 换行符有三种情形:"<code>\n</code>"、"<code>\r</code>"、"
* <code>\r\n</code>"。
* <p/>
* <pre>
* StringUtil.chomp(null) = null
* StringUtil.chomp("") = ""
* StringUtil.chomp("abc \r") = "abc "
* StringUtil.chomp("abc\n") = "abc"
* StringUtil.chomp("abc\r\n") = "abc"
* StringUtil.chomp("abc\r\n\r\n") = "abc\r\n"
* StringUtil.chomp("abc\n\r") = "abc\n"
* StringUtil.chomp("abc\n\rabc") = "abc\n\rabc"
* StringUtil.chomp("\r") = ""
* StringUtil.chomp("\n") = ""
* StringUtil.chomp("\r\n") = ""
* </pre>
* <p/>
* </p>
*
* @param str 要处理的字符串
* @return 不以换行结尾的字符串,如果原始字串为<code>null</code>,则返回<code>null</code>
*/
public static String chomp(String str) {
if (str == null || str.length() == 0) {
return str;
}
if (str.length() == 1) {
char ch = str.charAt(0);
if (ch == '\r' || ch == '\n') {
return EMPTY_STRING;
} else {
return str;
}
}
int lastIdx = str.length() - 1;
char last = str.charAt(lastIdx);
if (last == '\n') {
if (str.charAt(lastIdx - 1) == '\r') {
lastIdx--;
}
} else if (last == '\r') {
} else {
lastIdx++;
}
return str.substring(0, lastIdx);
}
/**
* 删除字符串末尾的指定字符串。如果字符串不以该字符串结尾,则什么也不做。
* <p/>
* <pre>
* StringUtil.chomp(null, *) = null
* StringUtil.chomp("", *) = ""
* StringUtil.chomp("foobar", "bar") = "foo"
* StringUtil.chomp("foobar", "baz") = "foobar"
* StringUtil.chomp("foo", "foo") = ""
* StringUtil.chomp("foo ", "foo") = "foo "
* StringUtil.chomp(" foo", "foo") = " "
* StringUtil.chomp("foo", "foooo") = "foo"
* StringUtil.chomp("foo", "") = "foo"
* StringUtil.chomp("foo", null) = "foo"
* </pre>
*
* @param str 要处理的字符串
* @param separator 要删除的字符串
* @return 不以指定字符串结尾的字符串,如果原始字串为<code>null</code>,则返回<code>null</code>
*/
public static String chomp(String str, String separator) {
if (str == null || str.length() == 0 || separator == null) {
return str;
}
if (str.endsWith(separator)) {
return str.substring(0, str.length() - separator.length());
}
return str;
}
/**
* 删除最后一个字符。
* <p>
* 如果字符串以<code>\r\n</code>结尾,则同时删除它们。
* <p/>
* <pre>
* StringUtil.chop(null) = null
* StringUtil.chop("") = ""
* StringUtil.chop("abc \r") = "abc "
* StringUtil.chop("abc\n") = "abc"
* StringUtil.chop("abc\r\n") = "abc"
* StringUtil.chop("abc") = "ab"
* StringUtil.chop("abc\nabc") = "abc\nab"
* StringUtil.chop("a") = ""
* StringUtil.chop("\r") = ""
* StringUtil.chop("\n") = ""
* StringUtil.chop("\r\n") = ""
* </pre>
* <p/>
* </p>
*
* @param str 要处理的字符串
* @return 删除最后一个字符的字符串,如果原始字符串为<code>null</code>,则返回<code>null</code>
*/
public static String chop(String str) {
if (str == null) {
return null;
}
int strLen = str.length();
if (strLen < 2) {
return EMPTY_STRING;
}
int lastIdx = strLen - 1;
String ret = str.substring(0, lastIdx);
char last = str.charAt(lastIdx);
if (last == '\n') {
if (ret.charAt(lastIdx - 1) == '\r') {
return ret.substring(0, lastIdx - 1);
}
}
return ret;
}
// ==========================================================================
// 反转字符串。
// ==========================================================================
/**
* 反转字符串中的字符顺序。
* <p>
* 如果字符串为<code>null</code>,则返回<code>null</code>。
* </p>
* <p/>
* <pre>
* StringUtil.reverse(null) = null
* StringUtil.reverse("") = ""
* StringUtil.reverse("bat") = "tab"
* </pre>
*
* @param str 要反转的字符串
* @return 反转后的字符串,如果原字符串为<code>null</code>,则返回<code>null</code>
*/
public static String reverse(String str) {
if (str == null || str.length() == 0) {
return str;
}
return new StringBuilder(str).reverse().toString();
}
/**
* 反转指定分隔符分隔的各子串的顺序。
* <p>
* 如果字符串为<code>null</code>,则返回<code>null</code>。
* </p>
* <p/>
* <pre>
* StringUtil.reverseDelimited(null, *) = null
* StringUtil.reverseDelimited("", *) = ""
* StringUtil.reverseDelimited("a.b.c", 'x') = "a.b.c"
* StringUtil.reverseDelimited("a.b.c", '.') = "c.b.a"
* </pre>
*
* @param str 要反转的字符串
* @param separatorChar 分隔符
* @return 反转后的字符串,如果原字符串为<code>null</code>,则返回<code>null</code>
*/
public static String reverseDelimited(String str, char separatorChar) {
if (str == null) {
return null;
}
String[] strs = split(str, separatorChar);
arrayReverse(strs);
return join(strs, String.valueOf(separatorChar));
}
/**
* 反转指定分隔符分隔的各子串的顺序。
* <p>
* 如果字符串为<code>null</code>,则返回<code>null</code>。
* </p>
* <p/>
* <pre>
* StringUtil.reverseDelimited(null, *, *) = null
* StringUtil.reverseDelimited("", *, *) = ""
* StringUtil.reverseDelimited("a.b.c", null, null) = "a.b.c"
* StringUtil.reverseDelimited("a.b.c", "", null) = "a.b.c"
* StringUtil.reverseDelimited("a.b.c", ".", ",") = "c,b,a"
* StringUtil.reverseDelimited("a.b.c", ".", null) = "c b a"
* </pre>
*
* @param str 要反转的字符串
* @param separatorChars 分隔符,如果为<code>null</code>,则默认使用空白字符
* @param separator 用来连接子串的分隔符,如果为<code>null</code>,默认使用空格
* @return 反转后的字符串,如果原字符串为<code>null</code>,则返回<code>null</code>
*/
public static String reverseDelimited(String str, String separatorChars, String separator) {
if (str == null) {
return null;
}
String[] strs = split(str, separatorChars);
arrayReverse(strs);
if (separator == null) {
return join(strs, " ");
}
return join(strs, separator);
}
// ==========================================================================
// 取得字符串的缩略。
// ==========================================================================
/**
* 将字符串转换成指定长度的缩略,例如:
* 将"Now is the time for all good men"转换成"Now is the time for..."。
* <ul>
* <li>如果<code>str</code>比<code>maxWidth</code>短,直接返回;</li>
* <li>否则将它转换成缩略:<code>substring(str, 0, max-3) + "..."</code>;</li>
* <li>如果<code>maxWidth</code>小于<code>4</code>抛出
* <code>IllegalArgumentException</code>;</li>
* <li>返回的字符串不可能长于指定的<code>maxWidth</code>。</li>
* </ul>
* <p/>
* <pre>
* StringUtil.abbreviate(null, *) = null
* StringUtil.abbreviate("", 4) = ""
* StringUtil.abbreviate("abcdefg", 6) = "abc..."
* StringUtil.abbreviate("abcdefg", 7) = "abcdefg"
* StringUtil.abbreviate("abcdefg", 8) = "abcdefg"
* StringUtil.abbreviate("abcdefg", 4) = "a..."
* StringUtil.abbreviate("abcdefg", 3) = IllegalArgumentException
* </pre>
*
* @param str 要检查的字符串
* @param maxWidth 最大长度,不小于<code>4</code>,如果小于<code>4</code>,则看作
* <code>4</code>
* @return 字符串缩略,如果原始字符串为<code>null</code>则返回<code>null</code>
*/
public static String abbreviate(String str, int maxWidth) {
return abbreviate(str, 0, maxWidth);
}
/**
* 将字符串转换成指定长度的缩略,例如:
* 将"Now is the time for all good men"转换成"...is the time for..."。
* <p>
* 和<code>abbreviate(String, int)</code>类似,但是增加了一个“左边界”偏移量。
* 注意,“左边界”处的字符未必出现在结果字符串的最左边,但一定出现在结果字符串中。
* </p>
* <p>
* 返回的字符串不可能长于指定的<code>maxWidth</code>。
* <p/>
* <pre>
* StringUtil.abbreviate(null, *, *) = null
* StringUtil.abbreviate("", 0, 4) = ""
* StringUtil.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
* StringUtil.abbreviate("abcdefghijklmno", 0, 10) = "abcdefg..."
* StringUtil.abbreviate("abcdefghijklmno", 1, 10) = "abcdefg..."
* StringUtil.abbreviate("abcdefghijklmno", 4, 10) = "abcdefg..."
* StringUtil.abbreviate("abcdefghijklmno", 5, 10) = "...fghi..."
* StringUtil.abbreviate("abcdefghijklmno", 6, 10) = "...ghij..."
* StringUtil.abbreviate("abcdefghijklmno", 8, 10) = "...ijklmno"
* StringUtil.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
* StringUtil.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
* StringUtil.abbreviate("abcdefghij", 0, 3) = IllegalArgumentException
* StringUtil.abbreviate("abcdefghij", 5, 6) = IllegalArgumentException
* </pre>
* <p/>
* </p>
*
* @param str 要检查的字符串
* @param offset 左边界偏移量
* @param maxWidth 最大长度,不小于<code>4</code>,如果小于<code>4</code>,则看作
* <code>4</code>
* @return 字符串缩略,如果原始字符串为<code>null</code>则返回<code>null</code>
*/
public static String abbreviate(String str, int offset, int maxWidth) {
if (str == null) {
return null;
}
// 调整最大宽度
if (maxWidth < 4) {
maxWidth = 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) {
maxWidth = 7;
}
if (offset + maxWidth - 3 < str.length()) {
return "..." + abbreviate(str.substring(offset), maxWidth - 3);
}
return "..." + str.substring(str.length() - (maxWidth - 3));
}
// ==========================================================================
// 比较两个字符串的异同。
// ==========================================================================
/**
* 比较两个字符串,取得第二个字符串中,和第一个字符串不同的部分。
* <p/>
* <pre>
* StringUtil.difference("i am a machine", "i am a robot") = "robot"
* StringUtil.difference(null, null) = null
* StringUtil.difference("", "") = ""
* StringUtil.difference("", null) = ""
* StringUtil.difference("", "abc") = "abc"
* StringUtil.difference("abc", "") = ""
* StringUtil.difference("abc", "abc") = ""
* StringUtil.difference("ab", "abxyz") = "xyz"
* StringUtil.difference("abcde", "abxyz") = "xyz"
* StringUtil.difference("abcde", "xyz") = "xyz"
* </pre>
*
* @param str1 字符串1
* @param str2 字符串2
* @return 第二个字符串中,和第一个字符串不同的部分。如果两个字符串相同,则返回空字符串<code>""</code>
*/
public static String difference(String str1, String str2) {
if (str1 == null) {
return str2;
}
if (str2 == null) {
return str1;
}
int index = indexOfDifference(str1, str2);
if (index == -1) {
return EMPTY_STRING;
}
return str2.substring(index);
}
/**
* 比较两个字符串,取得两字符串开始不同的索引值。
* <p/>
* <pre>
* StringUtil.indexOfDifference("i am a machine", "i am a robot") = 7
* StringUtil.indexOfDifference(null, null) = -1
* StringUtil.indexOfDifference("", null) = -1
* StringUtil.indexOfDifference("", "") = -1
* StringUtil.indexOfDifference("", "abc") = 0
* StringUtil.indexOfDifference("abc", "") = 0
* StringUtil.indexOfDifference("abc", "abc") = -1
* StringUtil.indexOfDifference("ab", "abxyz") = 2
* StringUtil.indexOfDifference("abcde", "abxyz") = 2
* StringUtil.indexOfDifference("abcde", "xyz") = 0
* </pre>
*
* @param str1 字符串1
* @param str2 字符串2
* @return 两字符串开始产生差异的索引值,如果两字符串相同,则返回<code>-1</code>
*/
public static int indexOfDifference(String str1, String str2) {
if (str1 == str2 || str1 == null || str2 == null) {
return -1;
}
int i;
for (i = 0; i < str1.length() && i < str2.length(); ++i) {
if (str1.charAt(i) != str2.charAt(i)) {
break;
}
}
if (i < str2.length() || i < str1.length()) {
return i;
}
return -1;
}
// ==========================================================================
// 将数字或字节转换成ASCII字符串的函数。
// ==========================================================================
private static final char[] DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
private static final char[] DIGITS_NOCASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
/** 将一个长整形转换成62进制的字符串。 */
public static String longToString(long longValue) {
return longToString(longValue, false);
}
/** 将一个长整形转换成62进制的字符串。 */
public static String longToString(long longValue, boolean noCase) {
char[] digits = noCase ? DIGITS_NOCASE : DIGITS;
int digitsLength = digits.length;
if (longValue == 0) {
return String.valueOf(digits[0]);
}
if (longValue < 0) {
longValue = -longValue;
}
StringBuilder strValue = new StringBuilder();
while (longValue != 0) {
int digit = (int) (longValue % digitsLength);
longValue = longValue / digitsLength;
strValue.append(digits[digit]);
}
return strValue.toString();
}
/** 将一个byte数组转换成62进制的字符串。 */
public static String bytesToString(byte[] bytes) {
return bytesToString(bytes, false);
}
/** 将一个byte数组转换成62进制的字符串。 */
public static String bytesToString(byte[] bytes, boolean noCase) {
char[] digits = noCase ? DIGITS_NOCASE : DIGITS;
int digitsLength = digits.length;
if (isEmptyArray(bytes)) {
return String.valueOf(digits[0]);
}
StringBuilder strValue = new StringBuilder();
int value = 0;
int limit = Integer.MAX_VALUE >>> 8;
int i = 0;
do {
while (i < bytes.length && value < limit) {
value = (value << 8) + (0xFF & bytes[i++]);
}
while (value >= digitsLength) {
strValue.append(digits[value % digitsLength]);
value = value / digitsLength;
}
} while (i < bytes.length);
if (value != 0 || strValue.length() == 0) {
strValue.append(digits[value]);
}
return strValue.toString();
}
// ==========================================================================
// 缩进排版函数。
// ==========================================================================
private final static Pattern CRLF_PATTERN = Pattern.compile("\\r|\\n|\\r\\n");
/** 从第二行开始,对每一行缩进指定空白。 */
public static String indent(String str, String indent) {
if (isEmpty(str)) {
return str;
}
StringBuilder buf = new StringBuilder();
indent(buf, str, indent);
return buf.toString();
}
/** 从第二行开始,对每一行缩进指定空白。 */
public static void indent(Formatter buf, String str, String indent) {
if (buf.out() instanceof StringBuilder) {
indent((StringBuilder) buf.out(), str, indent);
} else {
buf.format("%s", indent(str, indent));
}
}
/** 从第二行开始,对每一行缩进指定空白。 */
public static void indent(StringBuilder buf, String str, String indent) {
if (isEmpty(str)) {
return;
}
indent = defaultIfNull(indent, EMPTY_STRING);
if (isEmpty(indent)) {
buf.append(str);
return;
}
Matcher matcher = CRLF_PATTERN.matcher(str);
int index = 0;
while (matcher.find()) {
if (index < matcher.start() && index > 0) {
buf.append(indent);
}
buf.append(str, index, matcher.end());
index = matcher.end();
}
if (index < str.length()) {
if (index > 0) {
buf.append(indent);
}
buf.append(str, index, str.length());
}
}
}