对字符String进行处理
/******************************************************************************* * Copyright (c) 2013. Pyrlong 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.icos.utility.string; import java.io.UnsupportedEncodingException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.String.valueOf; /** * 处理字符串的工具类. * * @version 2.0 */ public class StringUtil { /** * 空字符常量 */ public static final String EMPTY = ""; /** * 索引字符数 */ public static final int INDEX_NOT_FOUND = -1; static FixSizeMap<String, Pattern> cachedPattern = null; /** * 限制字符数 */ @SuppressWarnings("unused") private static final int PAD_LIMIT = 8192; // private static Logger logger = Logger.getLogger(StringUtil.class); /** * Instantiates a new string util. */ public StringUtil() { super(); } public static int getCRC32INTID(String str) { int[] table = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d, }; byte[] bytes = str.getBytes(); int crc = 0xffffffff; for (byte b : bytes) { crc = (crc >>> 8 ^ table[(crc ^ b) & 0xff]); } crc = crc ^ 0xffffffff; // return Integer.toHexString(crc); return crc; } public static String pad(int colLength, int tabPos) { StringBuilder sAppend = new StringBuilder(); for (int len = tabPos - colLength; len != -1; len--) { sAppend.append(' '); } return sAppend.toString(); } public static String paint(char c, int amount) { StringBuilder append = new StringBuilder(); for (; amount != -1; amount--) { append.append(c); } return append.toString(); } public static String padTwo(Object first, Object second, int tab) { return new StringBuilder(valueOf(first)).append(pad(valueOf(first).length(), tab)).append(second).toString(); } /** * 功能描述: 判读字符序列为空 * * @param cs * CharSequence实例 * @return boolean 布尔值 * @since 2011.02.24 */ public static boolean isEmpty(CharSequence cs) { return cs == null || cs.length() == 0; } public static Object strDecode1(String input, Object name, Object value, Object elseValue) { return strDecode(input, name, value, elseValue); } public static Object strDecode(String input, Object... args) { int count = args.length; if (count == 0) return input; Object name = null; Object value = null; for (Object o : args) { if (name == null) { name = o; } else if (value == null) { value = o; if (input.equals(name)) return value; name = null; value = null; } } if (args.length % 2 == 1) return args[args.length - 1]; return input; } /** * 功能描述:判断字符序列不空 * * @param cs * CharSequence实例 * @return boolean 布尔值 * @since 2011.02.24 */ public static boolean isNotEmpty(CharSequence cs) { return !StringUtil.isEmpty(cs); } /** * 功能描述: 判断字符序列是空格 * * @param cs * CharSequence实例 * @return boolean 布尔值 * @since 2011.02.24 */ public static boolean isBlank(CharSequence cs) { int strLen; if (cs == null || (strLen = cs.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if ((Character.isWhitespace(cs.charAt(i)) == false)) { return false; } } return true; } /** * 功能描述: 判断字符序列不是空格 * * @param cs * CharSequence实例 * @return boolean 布尔值 * @since 2011.02.24 */ public static boolean isNotBlank(CharSequence cs) { return !StringUtil.isBlank(cs); } /** * Trim. * * @param str * the str * @return the string */ public static String trim(String str) { return str == null ? null : str.trim(); } /** * 功能描述: 判断字符序列是空格,还是为null * * @param str * String对象 * @return String 返回一个字符串 * @since 2011.02.24 */ public static String trimToNull(String str) { String ts = trim(str); return isEmpty(ts) ? null : ts; } /** * 功能描述: 判断字符序列是空格,还是为空 * * @param str * String对象 * @return String 返回一个字符串 * @since 2011.02.24 */ public static String trimToEmpty(String str) { return str == null ? EMPTY : str.trim(); } /** * 功能描述:给定2个字符串,进行比较 * * @param str1 * String对象 * @param str2 * String对象 * @return boolean 布尔值 * @since 2011.02.24 */ public static boolean equalsIgnoreCase(String str1, String str2) { return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2); } /** * 功能描述:给定一个字符串,和一个字符所在的位置,返回这一字符的位置 * * @param str * String对象 * @param searchChar * int类型数值 * @return int int类型数值 * @since 2011.02.24 */ public static int indexOf(String str, int searchChar) { if (isEmpty(str)) { return INDEX_NOT_FOUND; } return str.indexOf(searchChar); } /** * 功能描述:给定一个字符串,和一个字符所在的位置,以及一个索引数组;得到之间的间隔的字符数值 * * @param str * String对象 * @param searchChar * int类型数值 * @param startPos * int类型数值 * @return int int类型数值 * @since 2011.02.24 */ public static int indexOf(String str, int searchChar, int startPos) { if (isEmpty(str)) { return INDEX_NOT_FOUND; } return str.indexOf(searchChar, startPos); } /** * 功能描述:给定2个字符串,查询第二个字符串,在第一个字符串中的位置 * * @param str * String对象 * @param searchStr * String类型数值 * @return int int类型数值 * @since 2011.02.24 */ public static int indexOf(String str, String searchStr) { if (str == null || searchStr == null) { return INDEX_NOT_FOUND; } return str.indexOf(searchStr); } /** * 功能描述:给定一个字符串,和一个int值;判断这个索引值,是否存在 * * @param str * String对象 * @return boolean 布尔值 * @since 2011.02.24 */ public static boolean contains(String str, int searchChar) { if (isEmpty(str)) { return false; } return str.indexOf(searchChar) >= 0; } /** * 功能描述:给定2个字符串;判断第二个字符串是否在第一个字符串中存在 * * @param str * String对象 * @param searchStr * String对象 * @return boolean 布尔值 * @since 2011.02.24 */ public static boolean contains(String str, String searchStr) { if (str == null || searchStr == null) { return false; } return str.indexOf(searchStr) >= 0; } /** * 功能描述:给定一个字符串,判断字符串中是否有空格 * * @param str * String对象 * @return boolean 布尔值 * @since 2011.02.24 */ public static boolean containsWhitespace(String str) { if (isEmpty(str)) { return false; } int strLen = str.length(); for (int i = 0; i < strLen; i++) { if (Character.isWhitespace(str.charAt(i))) { return true; } } return false; } /** * 功能描述:给定一个字符串,和一个int类型的数值;得到一个子串 * * @param str * String对象 * @param start * int类型数值 * @return String 字符串 * @since 2011.02.24 */ public static String substring(String str, int start) { if (str == null) { return null; } if (start < 0) { start = str.length() + start; // remember start is negative } if (start < 0) { start = 0; } if (start > str.length()) { return EMPTY; } return str.substring(start); } /** * 功能描述:给定一个字符串,和两个int类型的数值;得到一个子串 * * @param str * String对象 * @param start * int类型数值 * @param end * int类型数值 * @return String 字符串 * @since 2011.02.24 */ public static String substring(String str, int start, int end) { if (str == null) { return null; } // handle negatives if (end < 0) { end = str.length() + end; // remember end is negative } if (start < 0) { start = str.length() + start; // remember start is negative } // check length next if (end > str.length()) { end = str.length(); } // if start is greater than end, return "" if (start > end) { return EMPTY; } if (start < 0) { start = 0; } if (end < 0) { end = 0; } return str.substring(start, end); } /** * 功能描述:给定一个字符串,和一个int类型的数值;得到0 到这个int类型之间的字符串 * * @param str * String对象 * @param len * int类型数值 * @return String 字符串 * @since 2011.02.24 */ public static String left(String str, int len) { if (str == null) { return null; } if (len < 0) { return EMPTY; } if (str.length() <= len) { return str; } return str.substring(0, len); } /** * 功能描述:给定一个字符串,删除这个字符之中的的空格 * * @param str * String对象 * @return String 字符串 * @since 2011.02.24 */ 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); } /** * 功能描述:给定一个字符串,和一个字符。删除这个字符在字符串中的位置 * * @param str * String对象 * @return String 字符串 * @since 2011.02.24 */ public static String remove(String str, char remove) { if (isEmpty(str) || str.indexOf(remove) == INDEX_NOT_FOUND) { 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); } /** * 功能描述:给定两个字符串,找到这两个字符串中字符匹配的个数 * * @param str * String对象 * @param sub * String对象 * @return int int类型数值 * @since 2011.02.24 */ public static int countMatches(String str, String sub) { if (isEmpty(str) || isEmpty(sub)) { return 0; } int count = 0; int idx = 0; while ((idx = str.indexOf(sub, idx)) != INDEX_NOT_FOUND) { count++; idx += sub.length(); } return count; } /** * 功能描述:判断是否为null或空值 * * @param str * String对象 * @return boolean 布尔值 * @since 2011.02.24 */ public static boolean isBlank(String str) { return str == null || str.trim().length() == 0 || "null".equalsIgnoreCase(str) || "undefined".equalsIgnoreCase(str) || str == ""; } /** * 功能描述:判断一个List对象为空;或是空对象 * * @param l * List对象 * @return boolean 布尔值 * @since 2011.02.24 */ public static boolean isBlank(List l) { return l == null || l.size() == 0; } /** * 功能描述:判断一个字符串数组对象为空;或是空对象 * * @param strArray * String[]对象 * @return boolean 布尔值 * @since 2011.02.24 */ public static boolean isBlank(String[] strArray) { return strArray == null || strArray.length == 0; } /** * 功能描述: 将对象转换为String,如果对象为null,则返回 "" * * @param object * 任意的Object对象 * @return String String对象 * @since 2011.02.24 */ public static String toString(Object object) { return (object == null ? "" : object.toString().trim()); } /** * 功能描述: 转换成两位小数 * * @param dDouble * Double对象 * @return Double Double对象 * @since 2011.02.24 */ public static Double formatDigitDouble(Double dDouble) { return (double) Math.round(dDouble * 100) / 100; } /** * 功能描述: 给定一个字符串,得到一个表达式字符串 * * @param temp * String对象 * @return String String对象 * @since 2011.02.24 */ public static String getExpressionString(String temp) { try { temp = temp.replace(']', '['); StringBuilder sb = new StringBuilder(); Boolean append = true; do { int index = temp.indexOf("["); if (append) { sb.append(temp.substring(0, index)); append = false; } else { append = true; } temp = temp.substring(index + 1); } while (temp.contains("[")); sb.append(temp); temp = sb.toString(); temp = temp.replace("||", "或"); temp = temp.replace("&&", "且"); return temp; } catch (Exception ex) { ex.printStackTrace(); return temp; } } /** * 功能描述: 字符串转换 * * @param temp * String对象 * @return String String对象 * @since 2011.02.24 */ public static String convertString(String temp) { if (temp == null) { return ""; } else { return temp; } } /** * 将byte[]转换为String类型(使用默认字符集) * * @param target * 要转换的byte[] * @return String 转换后的结果 */ public static String bytesToString(byte[] target) { return new String(target); } /** * 将byte[]转换为String类型 * * @param target * 要转换的byte[] * @param charsetName * 字符集名称 * @return String 转换后的结果 * @throws UnsupportedEncodingException */ public static String bytesToString(byte[] target, String charsetName) throws UnsupportedEncodingException { return new String(target, charsetName); } /** * 将int类型转换为byte[] * * @param target * 要转换的int * @return byte[] 转换后的结果 */ public static byte[] intToBytes(int target) { byte[] digit = new byte[4]; digit[3] = (byte) target; digit[2] = (byte) (target >> 8); digit[1] = (byte) (target >> 16); digit[0] = (byte) (target >> 24); return digit; } /** * 将long类型转换为byte[] * * @param target * 要转换的long * @return byte[] 转换后的结果 */ public static byte[] longToBytes(long target) { byte[] digit = new byte[8]; digit[7] = (byte) target; digit[6] = (byte) (target >> 8); digit[5] = (byte) (target >> 16); digit[4] = (byte) (target >> 24); digit[3] = (byte) (target >> 32); digit[2] = (byte) (target >> 40); digit[1] = (byte) (target >> 48); digit[0] = (byte) (target >> 56); return digit; } /** * 将String类型转换为byte[](使用默认字符集) * * @param target * 要转换的String * @return byte[] 转换后的结果 */ public static byte[] stringToBytes(String target) { return target.getBytes(); } /** * 将String类型转换为byte[] * * @param target * 要转换的String * @param charsetName * 字符集名称 * @return byte[] 转换后的结果 * @throws UnsupportedEncodingException */ public static byte[] stringToBytes(String target, String charsetName) throws UnsupportedEncodingException { return target.getBytes(charsetName); } public static String replaceLineationToNull(String str) { if (!isBlank(str)) { if (str.trim().equals("-") || str.trim().equals("--")) { return ""; } else { return str.trim(); } } return ""; } /** * 分析分隔符,并将特殊分隔符进行转义 * * @param strLine * @return */ public static String replaceSpcChar(String strLine) { StringBuffer st = new StringBuffer(); for (int n = 0; n < strLine.length(); n++) { char ch = strLine.charAt(n); if (ch == '|' || ch == '$' || ch == '\\' || ch == '.') { st.append("\\"); } st.append(ch); } return st.toString(); } /** * @param value * @return */ public static String getString(Object value) { if (value instanceof Date) { return ((Date) value).toString(); } else { return value == null ? "" : value.toString(); } } public static boolean isNullObjOrNotString(Object obj) { if (null == obj || !(obj instanceof String)) { return true; } return false; } /* * 将多个文本字符串合并成一个(最多支持30个) * * @param text it's type must be String or List */ public static String concatText(Object text) { String returnValue = null; StringBuilder sb = null; if (null == text) { return returnValue; } else { if (text instanceof String) { sb = new StringBuilder(); String[] strs = text.toString().split(","); for (int m = 0; m < strs.length; m++) { sb.append(strs[m]); } returnValue = sb.toString(); } else if (text instanceof List) { List list = (List) text; if (list.size() > 30) { list = list.subList(0, 29); } Iterator it = (list).listIterator(); sb = new StringBuilder(); while (it.hasNext()) { sb.append(it.next()); } returnValue = sb.toString(); } } return returnValue; } /* * 比较两个字符串是否完全相同(区分大小写),返回 真 或 假 * * @param textFirst it's type must be String or Null * * @param textSecond it's type must be String or Null */ public static boolean equals(Object textFirst, Object textSecond) { boolean bool = false; if (null == textFirst || null == textSecond) { return bool; } String stro1; String stro2; try { stro1 = getString(textFirst); stro2 = getString(textSecond); if (stro1.equals(stro2)) { bool = true; } } catch (Exception ex) { System.out.println(ex.getMessage()); } return bool; } /** * 对输入字符串正序排列并返回 * * @param list * @return * @author James Cheung Date:Jul 24, 2012 */ public List<String> sortListAsc(List<String> list) { return list; } /** * 对输入字符串反向排列 * * @param list * @return * @author James Cheung Date:Jul 24, 2012 */ public List<String> sortListDesc(List<String> list) { return list; } /* * 返回一个字符串在另外一个字符串出现的起始位置(区分大小写) * * @param child it's type must be String or Null * * @param parent it's type must be String or Null */ public static int startPosition(Object child, Object parent) { int position = -1; if (isNullObjOrNotString(child) || isNullObjOrNotString(parent)) { return position; } return parent.toString().indexOf(child.toString()); } /* * 返回字符串中的字符个数 * * @param text it's type must be String */ public static int getLength(Object text) { if (isNullObjOrNotString(text)) { return 0; } else { return text.toString().length(); } } /* * 将一个文本字符串的所有字母转换成为小写形式 * * @param text it's type must be String */ public static String toLower(Object text) { if (isNullObjOrNotString(text)) { return null; } else { return text.toString().toLowerCase(); } } public static boolean isNumber(Object obj) { if (obj == null || !(obj instanceof Number)) { return false; } return true; } /* * 从文本字符串中指定的起始位置返回指定长度的字符 * * @param text it's type must be String * * @param start it's type must be Ingteger * * @param size it's type must be Ingteger */ public static String getSubStr(Object text, Object start, Object size) { String returnStr = null; if (isNullObjOrNotString(text) || !(isNumber(start)) || !(isNumber(size))) { return returnStr; } int startIndex = Integer.valueOf(start.toString()) < 0 ? 0 : Integer.valueOf(start.toString()); int sizeLen = Integer.valueOf(size.toString()) < 1 ? 0 : Integer.valueOf(size.toString()); String str1 = text.toString(); int length = str1.length(); if (startIndex > str1.length() - 1) { return returnStr; } if ((startIndex + sizeLen) > length) { returnStr = str1.substring(startIndex, length); } else { returnStr = str1.substring(startIndex, (startIndex + sizeLen)); } return returnStr; } public static String replaceAll(String str, String regex, String newStr) { if (isEmpty(str)) return str; return str.replaceAll(regex, newStr); } /* * 将一个字符串中的部份字符用另一个字符串替换 */ /** * <p> * Replaces a String with another String inside a larger String, for the * first <code>max</code> values of the search String. * </p> * <p> * A <code>null</code> reference passed to this method is a no-op. * </p> * <p/> * * <pre> * StringFunctions.replace(null, *, *, *) = null * StringFunctions.replace("", *, *, *) = "" * StringFunctions.replace("any", null, *, *) = "any" * StringFunctions.replace("any", *, null, *) = "any" * StringFunctions.replace("any", "", *, *) = "any" * StringFunctions.replace("any", *, *, 0) = "any" * StringFunctions.replace("abaa", "a", null, -1) = "abaa" * StringFunctions.replace("abaa", "a", "", -1) = "b" * StringFunctions.replace("abaa", "a", "z", 0) = "abaa" * StringFunctions.replace("abaa", "a", "z", 1) = "zbaa" * StringFunctions.replace("abaa", "a", "z", 2) = "zbza" * StringFunctions.replace("abaa", "a", "z", -1) = "zbzz" * </pre> * * @param text * text to search and replace in, may be null * @param search * the String to search for, may be null * @param replace * the String to replace it with, may be null * @param max * maximum number of values to replace, or <code>-1</code> if no * maximum * @return the text with any replacements processed, <code>null</code> if * null String input */ public static String replaceChar(Object text, Object search, Object replace, Object max) { String textStr = null; if (isNullObjOrNotString(text) || null == search || null == replace || null == max) { return textStr; } String searchString = (String) search; String replacement = (String) replace; int maxValue = Integer.valueOf(max.toString()); textStr = text.toString(); int start = 0; int end = textStr.indexOf(searchString, start); if (end == INDEX_NOT_FOUND) { return textStr; } int replLength = searchString.length(); int increase = replacement.length() - replLength; increase = (increase < 0 ? 0 : increase); increase *= (maxValue < 0 ? 16 : (maxValue > 64 ? 64 : maxValue)); StringBuilder buf = new StringBuilder(textStr.length() + increase); while (end != INDEX_NOT_FOUND) { buf.append(textStr.substring(start, end)).append(replacement); start = end + replLength; if (--maxValue == 0) { break; } end = textStr.indexOf(searchString, start); } buf.append(textStr.substring(start)); return buf.toString(); } /** * <p> * Replaces all occurrences of Strings within another String. * </p> */ public static String splitFirst(String text, String regex) { String[] tempString = text.toString().split(regex.toString()); if (tempString.length > 0) { return tempString[0]; } return text.toString(); } public static String getSameItem(String text1, String text2) { String[] items1 = text1.split(","); String[] items2 = text2.split(","); List<String> list1 = new ArrayList<String>(); List<String> list2 = new ArrayList<String>(); for (String el : items1) { list1.add(el); } for (String el : items2) { list2.add(el); } list1.retainAll(list2); String text = listToString(list1, ','); return text; } public static String listToString(List list, char separator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.size(); i++) { sb.append(list.get(i)); if (i < list.size() - 1) { sb.append(separator); } } return sb.toString(); } /* * 将字符串中的部分字符串以新字符替换旧字符 * * @param str it's type must be String * * @param search it's type must be String * * @param replace it's type must be String */ public static String replace(Object text, Object search, Object replace) { if (isNullObjOrNotString(text) || isNullObjOrNotString(search) || isNullObjOrNotString(replace)) { return null; } String textStr = text.toString(); String result = textStr.replaceAll((String) search, (String) replace); return result; } /* * 根据指定次数重复文本。可用 REPT 在一个单元格中重复填写一个字符串 * * @param text it's type must be String * * @param search it's type must be String * * @param replace it's type must be String */ public static String addRepeatedText(Object text, Object addStr, Object times) { String textStr = null; if (isNullObjOrNotString(text) || isNullObjOrNotString(addStr) || !isNumber(times)) { return textStr; } textStr = text.toString(); StringBuilder sb = new StringBuilder(); sb.append(textStr); if (null == addStr || Integer.valueOf(times.toString()) <= 0) { textStr = sb.toString(); return textStr; } for (int i = 0; i < Integer.valueOf(times.toString()); i++) { sb.append(addStr.toString()); } textStr = sb.toString(); return textStr; } /** * 根据指定正则表达式获取匹配到的字符串 * * @param regx * 正则表达式配置 * @return 返回与指定字符串匹配的字符串,如果没有匹配则返回空 */ public static String getMatchString(String line, String regx) { String result = ""; Pattern pattern = getPattern(regx); Matcher matcher = pattern.matcher(line); if (matcher.find()) { result = matcher.group(); if (result.equalsIgnoreCase("NULL")) { result = ""; } return result; } return result; } /* * 从一个文本字符串的最后一个字符开始返回指定个数的字符 * * @param str it's type must be String * * @param count it's type must be Integer */ public static String subStringLast(Object text, Object count) { String textStr = null; if (isNullObjOrNotString(text) || !isNumber(count)) { return textStr; } String str = text.toString(); int length = str.length(); if (Integer.valueOf(count.toString()) < 1 || Integer.valueOf(count.toString()) > length) { return str; } else { return str.substring(length - Integer.valueOf(count.toString()), length); } } /* * 删除字符两头多余空格,但会保留词与词之间的空格 * * @param text it's type must be String */ public static String trim(Object text) { if (isNullObjOrNotString(text)) { return null; } return text.toString().trim(); } public static boolean isMatch(String line, String regex) { boolean result = false; if (StringUtil.isEmpty(regex) || StringUtil.isEmpty(line)) result = false; else { Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE); Matcher matcher = pattern.matcher(line); result = matcher.find(); } // if (!result) // logger.error("【" + regex + "】" + "【" + result + "】 \n" + line); return result; } /* * 将一个文本字符串的所有字母转换成为大写形式 * * @param text it's type must be String */ public static String upper(Object text) { if (isNullObjOrNotString(text)) { return null; } return text.toString().toUpperCase(); } public static int strLen(Object text) { return text.toString().length(); } private static Pattern getPattern(String regex) { if (cachedPattern == null) { cachedPattern = new FixSizeMap<String, Pattern>(); cachedPattern.setMaxSize(1000); } Pattern pattern = cachedPattern.get(regex); if (pattern == null) { pattern = Pattern.compile(regex, Pattern.MULTILINE); cachedPattern.put(regex, pattern); } return pattern; } /** * @Function : 根据传递字符串,和重复出现的字符.获得它在第N次出现的位置; * @param strParam * 要判断的字符串 * @param iIn * 指定出现的次数 * @param strChar * 指定的字符 */ public static int getCharPosition(String strParam, int iIn, String strChar) { // 这里是获取"/"符号的位置 Matcher slashMatcher = Pattern.compile(strChar).matcher(strParam); int mIdx = 0; while (slashMatcher.find()) { mIdx++; // 当strChar符号第N次出现的位置 if (mIdx == iIn) { break; } } int iPos = slashMatcher.start(); return iPos; } /** * @Function : 得到传入位数数字 * @param strNum * 要转换的数值 * @param len * 保留的位数 */ public static String getFormatNumber(float strNum, int len) { String ret = ""; String format = "#."; for (int i = 0; i < len; i++) { format += "0"; } // 负数处理 boolean minusFlag = false; if (strNum < 0) { minusFlag = true; strNum = Math.abs(strNum); } DecimalFormat df = new DecimalFormat(format); ret = df.format(strNum); if (strNum == 0) { return "0"; } if (strNum < 1) { ret = "0" + ret; } String preStr = ret; String point = ""; if (ret.indexOf(".") != -1) { String[] arr = ret.split("\\."); preStr = arr[0]; point = arr[1]; int pl = point.length() - 1; for (int i = pl; i >= 0; i--) { char p = point.charAt(i); if (p == '0') { point = point.substring(0, i); } else { break; } } } if ("".equals(point)) { ret = preStr; } else { ret = preStr + "." + point; } if (minusFlag) { ret = "-" + ret; } return ret; } public static String getFormatNumber(double strNum, int len) { String ret = ""; String format = "#."; for (int i = 0; i < len; i++) { format += "0"; } // 负数处理 boolean minusFlag = false; if (strNum < 0) { minusFlag = true; strNum = Math.abs(strNum); } DecimalFormat df = new DecimalFormat(format); ret = df.format(strNum); if (strNum == 0) { return "0"; } if (strNum < 1) { ret = "0" + ret; } String preStr = ret; String point = ""; if (ret.indexOf(".") != -1) { String[] arr = ret.split("\\."); preStr = arr[0]; point = arr[1]; int pl = point.length() - 1; for (int i = pl; i >= 0; i--) { char p = point.charAt(i); if (p == '0') { point = point.substring(0, i); } else { break; } } } if ("".equals(point)) { ret = preStr; } else { ret = preStr + "." + point; } if (minusFlag) { ret = "-" + ret; } return ret; } public static void main(String[] args) { int str = StringUtil.getCRC32INTID("123456"); boolean bool = StringUtil.isMatch("aabb|", "\\|"); System.out.println(bool); String str2 = "3-10662-1-73"; int iIn = StringUtil.getCharPosition(str2, 2, "-"); str2 = str2.substring(iIn + 1, str2.length()); System.out.println(str2); String str1 = StringUtil.getFormatNumber(-334.300f, 2); System.out.println(str1); } }