Field Summary | |
---|---|
static String |
EMPTY The empty String "" . |
static int |
INDEX_NOT_FOUND Represents a failed index search. |
Constructor Summary | |
---|---|
StringUtils() StringUtils instances should NOT be constructed in standard programming. |
Method Summary | |
---|---|
static String |
abbreviate(String str, int maxWidth) Abbreviates a String using ellipses. |
static String |
abbreviate(String str, int offset, int maxWidth) Abbreviates a String using ellipses. |
static String |
capitalise(String str) Deprecated. Use the standardly named capitalize(String) . Method will be removed in Commons Lang 3.0. |
static String |
capitaliseAllWords(String str) Deprecated. Use the relocated WordUtils.capitalize(String) . Method will be removed in Commons Lang 3.0. |
static String |
capitalize(String str) Capitalizes a String changing the first letter to title case as per Character.toTitleCase(char) . |
static String |
center(String str, int size) Centers a String in a larger String of size size using the space character (' '). |
static String |
center(String str, int size, char padChar) Centers a String in a larger String of size size . |
static String |
center(String str, int size, String padStr) Centers a String in a larger String of size size . |
static String |
chomp(String str) Removes one newline from end of a String if it's there, otherwise leave it alone. |
static String |
chomp(String str, String separator) Removes separator from the end of str if it's there, otherwise leave it alone. |
static String |
chompLast(String str) Deprecated. Use chomp(String) instead. Method will be removed in Commons Lang 3.0. |
static String |
chompLast(String str, String sep) Deprecated. Use chomp(String,String) instead. Method will be removed in Commons Lang 3.0. |
static String |
chop(String str) Remove the last character from a String. |
static String |
chopNewline(String str) Deprecated. Use chomp(String) instead. Method will be removed in Commons Lang 3.0. |
static String |
clean(String str) Deprecated. Use the clearer named trimToEmpty(String) . Method will be removed in Commons Lang 3.0. |
static String |
concatenate(Object[] array) Deprecated. Use the better named join(Object[]) instead. Method will be removed in Commons Lang 3.0. |
static boolean |
contains(String str, char searchChar) Checks if String contains a search character, handling null . |
static boolean |
contains(String str, String searchStr) Checks if String contains a search String, handling null . |
static boolean |
containsIgnoreCase(String str, String searchStr) Checks if String contains a search String irrespective of case, handling null . |
static boolean |
containsNone(String str, char[] invalidChars) Checks that the String does not contain certain characters. |
static boolean |
containsNone(String str, String invalidChars) Checks that the String does not contain certain characters. |
static boolean |
containsOnly(String str, char[] valid) Checks if the String contains only certain characters. |
static boolean |
containsOnly(String str, String validChars) Checks if the String contains only certain characters. |
static int |
countMatches(String str, String sub) Counts how many times the substring appears in the larger String. |
static String |
defaultIfEmpty(String str, String defaultStr) Returns either the passed in String, or if the String is empty or null , the value of defaultStr . |
static String |
defaultString(String str) Returns either the passed in String, or if the String is null , an empty String (""). |
static String |
defaultString(String str, String defaultStr) Returns either the passed in String, or if the String is null , the value of defaultStr . |
static String |
deleteSpaces(String str) Deprecated. Use the better localized deleteWhitespace(String) . Method will be removed in Commons Lang 3.0. |
static String |
deleteWhitespace(String str) Deletes all whitespaces from a String as defined by Character.isWhitespace(char) . |
static String |
difference(String str1, String str2) Compares two Strings, and returns the portion where they differ. |
static boolean |
equals(String str1, String str2) Compares two Strings, returning true if they are equal. |
static boolean |
equalsIgnoreCase(String str1, String str2) Compares two Strings, returning true if they are equal ignoring the case. |
static String |
escape(String str) Deprecated. Use StringEscapeUtils.escapeJava(String) This method will be removed in Commons Lang 3.0 |
static String |
getChomp(String str, String sep) Deprecated. Use substringAfterLast(String, String) instead (although this doesn't include the separator) Method will be removed in Commons Lang 3.0. |
static int |
getLevenshteinDistance(String s, String t) Find the Levenshtein distance between two Strings. |
static String |
getNestedString(String str, String tag) Deprecated. Use the better named substringBetween(String, String) . Method will be removed in Commons Lang 3.0. |
static String |
getNestedString(String str, String open, String close) Deprecated. Use the better named substringBetween(String, String, String) . Method will be removed in Commons Lang 3.0. |
static String |
getPrechomp(String str, String sep) Deprecated. Use substringBefore(String,String) instead (although this doesn't include the separator). Method will be removed in Commons Lang 3.0. |
static int |
indexOf(String str, char searchChar) Finds the first index within a String, handling null . |
static int |
indexOf(String str, char searchChar, int startPos) Finds the first index within a String from a start position, handling null . |
static int |
indexOf(String str, String searchStr) Finds the first index within a String, handling null . |
static int |
indexOf(String str, String searchStr, int startPos) Finds the first index within a String, handling null . |
static int |
indexOfAny(String str, char[] searchChars) Search a String to find the first index of any character in the given set of characters. |
static int |
indexOfAny(String str, String searchChars) Search a String to find the first index of any character in the given set of characters. |
static int |
indexOfAny(String str, String[] searchStrs) Find the first index of any of a set of potential substrings. |
static int |
indexOfAnyBut(String str, char[] searchChars) Search a String to find the first index of any character not in the given set of characters. |
static int |
indexOfAnyBut(String str, String searchChars) Search a String to find the first index of any character not in the given set of characters. |
static int |
indexOfDifference(String str1, String str2) Compares two Strings, and returns the index at which the Strings begin to differ. |
static boolean |
isAlpha(String str) Checks if the String contains only unicode letters. |
static boolean |
isAlphanumeric(String str) Checks if the String contains only unicode letters or digits. |
static boolean |
isAlphanumericSpace(String str) Checks if the String contains only unicode letters, digits or space ( ' ' ). |
static boolean |
isAlphaSpace(String str) Checks if the String contains only unicode letters and space (' '). |
static boolean |
isAsciiPrintable(String str) Checks if the string contains only ASCII printable characters. |
static boolean |
isBlank(String str) Checks if a String is whitespace, empty ("") or null. |
static boolean |
isEmpty(String str) Checks if a String is empty ("") or null. |
static boolean |
isNotBlank(String str) Checks if a String is not empty (""), not null and not whitespace only. |
static boolean |
isNotEmpty(String str) Checks if a String is not empty ("") and not null. |
static boolean |
isNumeric(String str) Checks if the String contains only unicode digits. |
static boolean |
isNumericSpace(String str) Checks if the String contains only unicode digits or space ( ' ' ). |
static boolean |
isWhitespace(String str) Checks if the String contains only whitespace. |
static String |
join(Collection collection, char separator) Joins the elements of the provided Collection into a single String containing the provided elements. |
static String |
join(Collection collection, String separator) Joins the elements of the provided Collection into a single String containing the provided elements. |
static String |
join(Iterator iterator, char separator) Joins the elements of the provided Iterator into a single String containing the provided elements. |
static String |
join(Iterator iterator, String separator) Joins the elements of the provided Iterator into a single String containing the provided elements. |
static String |
join(Object[] array) Joins the elements of the provided array into a single String containing the provided list of elements. |
static String |
join(Object[] array, char separator) Joins the elements of the provided array into a single String containing the provided list of elements. |
static String |
join(Object[] array, char separator, int startIndex, int endIndex) Joins the elements of the provided array into a single String containing the provided list of elements. |
static String |
join(Object[] array, String separator) Joins the elements of the provided array into a single String containing the provided list of elements. |
static String |
join(Object[] array, String separator, int startIndex, int endIndex) Joins the elements of the provided array into a single String containing the provided list of elements. |
static int |
lastIndexOf(String str, char searchChar) Finds the last index within a String, handling null . |
static int |
lastIndexOf(String str, char searchChar, int startPos) Finds the last index within a String from a start position, handling null . |
static int |
lastIndexOf(String str, String searchStr) Finds the last index within a String, handling null . |
static int |
lastIndexOf(String str, String searchStr, int startPos) Finds the first index within a String, handling null . |
static int |
lastIndexOfAny(String str, String[] searchStrs) Find the latest index of any of a set of potential substrings. |
static String |
left(String str, int len) Gets the leftmost len characters of a String. |
static String |
leftPad(String str, int size) Left pad a String with spaces (' '). |
static String |
leftPad(String str, int size, char padChar) Left pad a String with a specified character. |
static String |
leftPad(String str, int size, String padStr) Left pad a String with a specified String. |
static String |
lowerCase(String str) Converts a String to lower case as per String.toLowerCase() . |
static String |
mid(String str, int pos, int len) Gets len characters from the middle of a String. |
static int |
ordinalIndexOf(String str, String searchStr, int ordinal) Finds the n-th index within a String, handling null . |
static String |
overlay(String str, String overlay, int start, int end) Overlays part of a String with another String. |
static String |
overlayString(String text, String overlay, int start, int end) Deprecated. Use better named overlay(String, String, int, int) instead. Method will be removed in Commons Lang 3.0. |
static String |
prechomp(String str, String sep) Deprecated. Use substringAfter(String,String) instead. Method will be removed in Commons Lang 3.0. |
static String |
remove(String str, char remove) Removes all occurances of a character from within the source string. |
static String |
remove(String str, String remove) Removes all occurances of a substring from within the source string. |
static String |
removeEnd(String str, String remove) Removes a substring only if it is at the end of a source string, otherwise returns the source string. |
static String |
removeStart(String str, String remove) Removes a substring only if it is at the begining of a source string, otherwise returns the source string. |
static String |
repeat(String str, int repeat) Repeat a String repeat times to form a new String. |
static String |
replace(String text, String repl, String with) Replaces all occurrences of a String within another String. |
static String |
replace(String text, String repl, String with, int max) Replaces a String with another String inside a larger String, for the first max values of the search String. |
static String |
replaceChars(String str, char searchChar, char replaceChar) Replaces all occurrences of a character in a String with another. |
static String |
replaceChars(String str, String searchChars, String replaceChars) Replaces multiple characters in a String in one go. |
static String |
replaceOnce(String text, String repl, String with) Replaces a String with another String inside a larger String, once. |
static String |
reverse(String str) Reverses a String as per StringBuffer.reverse() . |
static String |
reverseDelimited(String str, char separatorChar) Reverses a String that is delimited by a specific character. |
static String |
reverseDelimitedString(String str, String separatorChars) Deprecated. Use reverseDelimited(String, char) instead. This method is broken as the join doesn't know which char to use. Method will be removed in Commons Lang 3.0. |
static String |
right(String str, int len) Gets the rightmost len characters of a String. |
static String |
rightPad(String str, int size) Right pad a String with spaces (' '). |
static String |
rightPad(String str, int size, char padChar) Right pad a String with a specified character. |
static String |
rightPad(String str, int size, String padStr) Right pad a String with a specified String. |
static String[] |
split(String str) Splits the provided text into an array, using whitespace as the separator. |
static String[] |
split(String str, char separatorChar) Splits the provided text into an array, separator specified. |
static String[] |
split(String str, String separatorChars) Splits the provided text into an array, separators specified. |
static String[] |
split(String str, String separatorChars, int max) Splits the provided text into an array with a maximum length, separators specified. |
static String[] |
splitByWholeSeparator(String str, String separator) Splits the provided text into an array, separator string specified. |
static String[] |
splitByWholeSeparator(String str, String separator, int max) Splits the provided text into an array, separator string specified. |
static String[] |
splitPreserveAllTokens(String str) Splits the provided text into an array, using whitespace as the separator, preserving all tokens, including empty tokens created by adjacent separators. |
static String[] |
splitPreserveAllTokens(String str, char separatorChar) Splits the provided text into an array, separator specified, preserving all tokens, including empty tokens created by adjacent separators. |
static String[] |
splitPreserveAllTokens(String str, String separatorChars) Splits the provided text into an array, separators specified, preserving all tokens, including empty tokens created by adjacent separators. |
static String[] |
splitPreserveAllTokens(String str, String separatorChars, int max) Splits the provided text into an array with a maximum length, separators specified, preserving all tokens, including empty tokens created by adjacent separators. |
static String |
strip(String str) Strips whitespace from the start and end of a String. |
static String |
strip(String str, String stripChars) Strips any of a set of characters from the start and end of a String. |
static String[] |
stripAll(String[] strs) Strips whitespace from the start and end of every String in an array. |
static String[] |
stripAll(String[] strs, String stripChars) Strips any of a set of characters from the start and end of every String in an array. |
static String |
stripEnd(String str, String stripChars) Strips any of a set of characters from the end of a String. |
static String |
stripStart(String str, String stripChars) Strips any of a set of characters from the start of a String. |
static String |
stripToEmpty(String str) Strips whitespace from the start and end of a String returning an empty String if null input. |
static String |
stripToNull(String str) Strips whitespace from the start and end of a String returning null if the String is empty ("") after the strip. |
static String |
substring(String str, int start) Gets a substring from the specified String avoiding exceptions. |
static String |
substring(String str, int start, int end) Gets a substring from the specified String avoiding exceptions. |
static String |
substringAfter(String str, String separator) Gets the substring after the first occurrence of a separator. |
static String |
substringAfterLast(String str, String separator) Gets the substring after the last occurrence of a separator. |
static String |
substringBefore(String str, String separator) Gets the substring before the first occurrence of a separator. |
static String |
substringBeforeLast(String str, String separator) Gets the substring before the last occurrence of a separator. |
static String |
substringBetween(String str, String tag) Gets the String that is nested in between two instances of the same String. |
static String |
substringBetween(String str, String open, String close) Gets the String that is nested in between two Strings. |
static String[] |
substringsBetween(String str, String open, String close) Searches a String for substrings delimited by a start and end tag, returning all matching substrings in an array. |
static String |
swapCase(String str) Swaps the case of a String changing upper and title case to lower case, and lower case to upper case. |
static String |
trim(String str) Removes control characters (char <= 32) from both ends of this String, handling null by returning null . |
static String |
trimToEmpty(String str) Removes control characters (char <= 32) from both ends of this String returning an empty String ("") if the String is empty ("") after the trim or if it is null . |
static String |
trimToNull(String str) Removes control characters (char <= 32) from both ends of this String returning null if the String is empty ("") after the trim or if it is null . |
static String |
uncapitalise(String str) Deprecated. Use the standardly named uncapitalize(String) . Method will be removed in Commons Lang 3.0. |
static String |
uncapitalize(String str) Uncapitalizes a String changing the first letter to title case as per Character.toLowerCase(char) . |
static String |
upperCase(String str) Converts a String to upper case as per String.toUpperCase() . |
import
java.util.Date;
import java.util. * ;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.StringCharacterIterator;
public class StringUtil {
// private StringUtil(){}
/**
* 将一个字串的首字母大写
* @param s String 源字串
* @return String 首字母大写后的字串
*/
public static String toUpperCaseFirstLetter(String s) {
return isNullStr(s)
? s
: s.substring( 0 , 1 ).toUpperCase() + s.substring( 1 );
}
/**
* 把空字符串转换为empty
* @param s
* @return
* @deprecated
* @see getNotNullStr
*/
public static final String nullToEmptyOfStr(String s) {
if (s != null )
return s.trim();
else
return "" ;
}
/**
*
* @param s
* @return
*/
public static final String escapeErrorChar(String s) {
String s1 = null ;
s1 = s;
if (s1 == null ) {
return s1;
} else {
s1 = replace(s1, " \\ " , " \\\\ " );
s1 = replace(s1, " \ "" , " \\\ "" );
return s1;
}
}
/**
* 取指定字符串的指定长度子字串
* @param strAll
* @param strLen
* @return
*/
public static final String subStr(String strAll, int strLen) {
String strNew = nullToEmptyOfStr(strAll);
String myStr = "" ;
if (strNew.length() >= strLen) {
myStr = strNew.substring( 0 , strLen);
} else {
myStr = strNew;
}
return myStr;
}
/*
public static final String streamToString(InputStream in)
{
StringBuffer sb=new StringBuffer("");
byte[] buffer = new byte[4096];
int bytes_read;
try
{
while ( (bytes_read = in.read(buffer)) != -1)
{
sb.append(new String(buffer, 0, bytes_read, "GBK"));
}
return sb.toString();
}
catch(Exception ex)
{
return null;
}
}
*/
public static final String replaceIgnoreCase(
String s,
String s1,
String s2) {
if (s == null )
return null ;
String s3 = s.toLowerCase();
String s4 = s1.toLowerCase();
int i = 0 ;
if ((i = s3.indexOf(s4, i)) >= 0 ) {
char ac[] = s.toCharArray();
char ac1[] = s2.toCharArray();
int j = s1.length();
StringBuffer stringbuffer = new StringBuffer(ac.length);
stringbuffer.append(ac, 0 , i).append(ac1);
i += j;
int k;
for (k = i;(i = s3.indexOf(s4, i)) > 0 ; k = i) {
stringbuffer.append(ac, k, i - k).append(ac1);
i += j;
}
stringbuffer.append(ac, k, ac.length - k);
return stringbuffer.toString();
} else {
return s;
}
}
public static final String formatInputStr(String s) {
String s1 = s;
s1 = nullToEmptyOfStr(s1);
s1 = escapeHTMLTags(s1);
return s1;
}
public static final String escapeHTMLTags(String s) {
if (s == null || s.length() == 0 )
return s;
StringBuffer stringbuffer = new StringBuffer(s.length());
byte byte0 = 32 ;
for ( int i = 0 ; i < s.length(); i ++ ) {
char c = s.charAt(i);
if (c == ' < ' )
stringbuffer.append( " < " );
else if (c == ' > ' )
stringbuffer.append( " > " );
else
stringbuffer.append(c);
}
return stringbuffer.toString();
}
// 字符串替换 s 搜索字符串 s1 要查找字符串 s2 要替换字符串
public static String replace(String s, String s1, String s2) {
if (s == null )
return null ;
int i = 0 ;
if ((i = s.indexOf(s1, i)) >= 0 ) {
char ac[] = s.toCharArray();
char ac1[] = s2.toCharArray();
int j = s1.length();
StringBuffer stringbuffer = new StringBuffer(ac.length);
stringbuffer.append(ac, 0 , i).append(ac1);
i += j;
int k;
for (k = i;(i = s.indexOf(s1, i)) > 0 ; k = i) {
stringbuffer.append(ac, k, i - k).append(ac1);
i += j;
}
stringbuffer.append(ac, k, ac.length - k);
return stringbuffer.toString();
} else {
return s;
}
}
public static String replace(String s, String s1, String s2, int ai[]) {
if (s == null )
return null ;
int i = 0 ;
if ((i = s.indexOf(s1, i)) >= 0 ) {
int j = 0 ;
j ++ ;
char ac[] = s.toCharArray();
char ac1[] = s2.toCharArray();
int k = s1.length();
StringBuffer stringbuffer = new StringBuffer(ac.length);
stringbuffer.append(ac, 0 , i).append(ac1);
i += k;
int l;
for (l = i;(i = s.indexOf(s1, i)) > 0 ; l = i) {
j ++ ;
stringbuffer.append(ac, l, i - l).append(ac1);
i += k;
}
stringbuffer.append(ac, l, ac.length - l);
ai[ 0 ] = j;
return stringbuffer.toString();
} else {
return s;
}
}
// 把字符串转换为向量
public static Vector splite(String s, String s1) {
Vector vector = new Vector();
Object obj = null ;
Object obj1 = null ;
boolean flag = false ;
int i;
for (; s.length() >= 0 ; s = s.substring(i + s1.length(), s.length())) {
i = s.indexOf(s1);
if (i < 0 ) {
vector.addElement(s);
break ;
}
String s2 = s.substring( 0 , i);
vector.addElement(s2);
}
return vector;
}
/**
* convert Array to ArrayList
* @param sz String[]
* @param len int
* @return ArrayList
*/
public static ArrayList getArrayListFromArray(String[] sz, int len) {
ArrayList aTmp = new ArrayList();
if (isNullStr(sz)) {
for ( int i = 0 ; i < len; i ++ ) {
aTmp.add( "" );
}
} else {
for ( int i = 0 ; i < sz.length; i ++ ) {
aTmp.add(sz[i]);
}
}
return aTmp;
}
/**
* Convert to int Base200312291149
* @param o Object
* @return int
*/
public static int cNum(Object o) {
try {
return Integer.parseInt(cStr(o));
} catch (Exception ex) {
return 0 ;
}
}
/**
* Convert to String from object Base200312291148
* @param o Object
* @return String
*/
public static String cStr(Object o) {
return o == null ? "" : o.toString();
}
/**
* 判断此字符串是否为空、空字符串,或"null"
* @param str
* @return
*/
public static boolean isNullStr(String s) {
return (s == null || s.equals( " null " ) || s.equals( "" )) ? true : false ;
}
/**
* 如果字符串为空、空字符串,或"null"时返回"0"
* @param str
* @return String
*/
public static String emptyToZero(String str) {
if (isNullStr(str))
return " 0 " ;
else
return str.trim();
}
/**
* 判断此字符串是否为空、空字符串,或"null"
* @param str
* @return
*/
public static boolean isNullStr(Object o) {
return (
o == null
|| o.toString().equals( " null " )
|| o.toString().equals( "" ))
?
// return (o==null||o.toString().equals(""))?
true : false ;
}
/**
* 如果字符串str为空则转换为str1
* @param str
* @param str1
* @return
*/
public static String getNullStr(String str, String str1) {
if (isNullStr(str))
return str1;
else
return str;
}
/**
* 将字符串str转换为GBK编码格式
* @param str
* @return
*/
public static String getGBKStr(String str) {
try {
String temp_p;
temp_p = str;
// temp_p = getNullStr(temp_p, "");
temp_p = nullToEmptyOfStr(temp_p);
byte [] temp_t = temp_p.getBytes( " ISO8859_1 " );
String temp = new String(temp_t, " GBK " );
return temp;
} catch (Exception e) {
return "" ;
}
}
public static String getISOStr(String str) {
try {
String temp_p;
temp_p = str;
temp_p = getNullStr(temp_p, "" );
byte [] temp_t = temp_p.getBytes( " ISO8859_1 " );
String temp = new String(temp_t);
return temp;
} catch (Exception e) {}
return " null " ;
}
/**
* 中文转换--文章换行的转换
* @param str
* @return
*/
public static String getText(String str) {
if (str == null )
return ( "" );
if (str.equals( "" ))
return ( "" );
// 建立一个StringBuffer来处理输入数据
StringBuffer buf = new StringBuffer(str.length() + 6 );
char ch = ' \n ' ;
for ( int i = 0 ; i < str.length(); i ++ ) {
ch = str.charAt(i);
if (ch == ' \n ' ) {
buf.append( " <br> " );
} else if (ch == ' \t ' ) {
buf.append( " " );
} else if (ch == ' ' ) {
buf.append( " " );
} else {
buf.append(ch);
}
}
return buf.toString();
}
/**
* 格式化复选框生成字串
* @param selectID
* @return
* @deprecated
* @see this.combineArray(String[] array)
*/
public static String getCheckbox(String[] selectID) {
String[] ss;
ss = selectID;
String temp = "" ;
try {
for ( int i = 0 ; i < ss.length; i ++ )
temp += ss[i] + " , " ;
if (temp.length() > 0 )
temp = temp.substring( 0 , temp.length() - 1 );
return temp;
} catch (NullPointerException e) {
return "" ;
}
}
/**
* 将字串转成日期,字串格式: yyyy/MM/dd
* @author Base200312111725
* @param string String
* @return Date
*/
public static Date toDate(String string) {
try {
DateFormat formatter = new SimpleDateFormat( " yyyy/MM/dd " );
return (Date) formatter.parse(string);
} catch (Exception ex) {
System.err.println(
" [ com.huanglq.util.StringUtil.toDate(string) ] "
+ ex.getMessage());
return null ;
}
}
/**
* 将字串转成日期和时间,字串格式: yyyy/MM/dd HH:mm:ss
* @author Base200312111726
* @param string String
* @return Date
*/
public static Date toDatetime(String string) {
try {
DateFormat formatter = new SimpleDateFormat( " yyyy/MM/dd HH:mm:ss " );
return (Date) formatter.parse(string);
} catch (Exception ex) {
System.err.println(
" [ com.huanglq.util.StringUtil.toDatetime(string) ] "
+ ex.getMessage());
return null ;
}
}
/**
* 判断单选框是否选中
* @author tempnc20031222
* @param inparam
* @param val
* @return 是否选中
*/
public static String isChecked(String inparam, String val) {
try {
if (inparam.trim().equals(val.trim()))
return " checked " ;
else
return "" ;
} catch (Exception ex) {
System.err.println(
" [ com.huanglq.util.StringUtil.toDatetime(string) ] "
+ ex.getMessage());
return null ;
}
}
public static void main(String[] argv) {
// StringUtil su = new StringUtil();
/*
System.out.println(
":" + StringUtil.toUpperCaseFirstLetter(""));
*/
String strTest = " 具备的资格:\n " +
" - 高级经理岗位资格证书(No.A100xxx),上海市人事局 \n " +
" - 科技管理专业高级工程师任职资格证书(No.01C4050xxx/1077xxx),上海市政府人事局 \n " +
" - ISO9000 执照 上海质量管理协会 \n " +
" - 原产地证书(No.960xxx/37xx),中国国际贸易促进委员会(CCPIT)上海市分会 \n " +
" - 中国通信学会有线传输专业委员会会员(No.31xx) \n " +
" - 上海化学化工学会高分子专业委员会会员(No.9-71xx) \n " +
" - 上海塑料工程学会塑料加工专业委员会会员 \n " +
" - 联系方式:手机/137 0168 8348石晓东, 电话及传真/(21)6433 8067石晓东, Email: [email protected], [email protected] \n " +
" - 联系方式:mail:[email protected] \n " +
" 传真/(21)6433 8067石晓东 " +
" 手机:137-2557-6014\n " ;
System.out.println(checkStr(strTest));
}
/**
* 根据转义列表对字符串进行转义(escape)。
* @param source 待转义的字符串
* @param escapeCharMap 转义列表
* @return 转义后的字符串
*/
public static String escapeCharacter(
String source,
HashMap escapeCharMap) {
if (source == null || source.length() == 0 ) {
return source;
}
if (escapeCharMap.size() == 0 ) {
return source;
}
StringBuffer sb = new StringBuffer(source.length() + 100 );
StringCharacterIterator sci = new StringCharacterIterator(source);
for ( char c = sci.first();
c != StringCharacterIterator.DONE;
c = sci.next()) {
String character = String.valueOf(c);
if (escapeCharMap.containsKey(character)) {
character = (String) escapeCharMap.get(character);
}
sb.append(character);
}
return sb.toString();
}
/**
* 此方法将给出的字符串source使用delim划分为单词数组。
* @param source 需要进行划分的原字符串
* @param delim 单词的分隔字符串
* @return 划分以后的数组,如果source为null的时候返回以source为唯一元素的数组,
* 如果delim为null则使用逗号作为分隔字符串。
* @since 0.1
*/
public static String[] split(String source, String delim) {
String[] wordLists;
if (source == null ) {
wordLists = new String[ 1 ];
wordLists[ 0 ] = source;
return wordLists;
}
if (delim == null ) {
delim = " , " ;
}
StringTokenizer st = new StringTokenizer(source, delim);
int total = st.countTokens();
wordLists = new String[total];
for ( int i = 0 ; i < total; i ++ ) {
wordLists[i] = st.nextToken();
}
return wordLists;
}
/**
* 此方法将给出的字符串source使用delim划分为单词数组。
* @param source 需要进行划分的原字符串
* @param delim 单词的分隔字符
* @return 划分以后的数组,如果source为null的时候返回以source为唯一元素的数组。
* @since 0.2
*/
public static String[] split(String source, char delim) {
return split(source, String.valueOf(delim));
}
/**
* 此方法将给出的字符串source使用逗号划分为单词数组。
* @param source 需要进行划分的原字符串
* @return 划分以后的数组,如果source为null的时候返回以source为唯一元素的数组。
* @since 0.1
*/
public static String[] split(String source) {
return split(source, " , " );
}
/**
* 将set的所有记录并成一个以 delim 分隔的字符串
* @param set
* @param delim
* @return
*/
public static String combine(Set set, String delim) {
if (set == null || set.size() == 0 ) {
return "" ;
}
if (delim == null ) {
delim = "" ;
}
StringBuffer sb = new StringBuffer( 100 );
for (Iterator iter = set.iterator(); iter.hasNext(); ) {
sb.append(iter.next());
sb.append(delim);
}
if (sb.length() >= delim.length()) {
sb.delete(sb.length() - 1 - delim.length(), sb.length() - 1 );
}
return sb.toString();
}
/**
* 将set的所有记录并成一个以 , 分隔的字符串
* @param set
* @param delim
* @return
*/
public static String combine(Set set) {
return combine(set, " , " );
}
/**
* 将字符串数组合并成一个以 delim 分隔的字符串
* @param array 字符串数组
* @param delim 分隔符,为null的时候使用""作为分隔符(即没有分隔符)
* @return 合并后的字符串
*/
public static String combineArray(String[] array, String delim) {
if (array == null || array.length == 0 ) {
return "" ;
}
int length = array.length - 1 ;
if (delim == null ) {
delim = "" ;
}
StringBuffer result = new StringBuffer(length * 8 );
for ( int i = 0 ; i < length; i ++ ) {
result.append(array[i]);
result.append(delim);
}
result.append(array[length]);
return result.toString();
}
/**
* 将字符串数组合并成一个以,号分隔的字符串
* @param array 字符串数组
* @return 合并后的字符串
*/
public static String combineArray(String[] array) {
return combineArray(array, " , " );
}
/**
* 将字符串数组使用指定的分隔符合并成一个字符串。
* @param array 字符串数组
* @param delim 分隔符,为null的时候使用""作为分隔符(即没有分隔符)
* @return 合并后的字符串
* @deprecated
*/
public static String combineStringArray(String[] array, String delim) {
return combineArray(array, delim);
}
/**
* 将int数组使用指定的分隔符合并成一个字符串
* @param array int[] int 数组
* @param delim String 分隔符,为null的时候使用""作为分隔符(即没有分隔符)
* @return String 合并后的字符串
*/
public static String combineArray( int [] array, String delim) {
if (array == null || array.length == 0 ) {
return "" ;
}
int length = array.length - 1 ;
if (delim == null ) {
delim = "" ;
}
StringBuffer result = new StringBuffer();
for ( int i = 0 ; i < length; i ++ ) {
result.append(Integer.toString(array[i]));
result.append(delim);
}
result.append(Integer.toString(array[length]));
return result.toString();
}
/**
* 将int数组合并成一个以,号分隔的字符串
* @param array 字符串数组
* @return 合并后的字符串
*/
public static String combineArray( int [] array) {
return combineArray(array, " , " );
}
/**
* 将字符串List使用指定的分隔符合并成一个字符串。
* @param list List
* @param delim String
* @return String
*/
public static String combineList(List list, String delim) {
if (list == null || list.size() == 0 ) {
return "" ;
} else {
StringBuffer result = new StringBuffer();
for ( int i = 0 ; i < list.size() - 1 ; i ++ ) {
result.append(list.get(i));
result.append(delim);
}
result.append(list.get(list.size() - 1 ));
return result.toString();
}
}
/**
* 将字符串List使用 , 合并成一个字符串。
* @param list List
* @return String
*/
public static String combineList(List list) {
return combineList(list, " , " );
}
/**
* 将字符串List使用指定的分隔符合并成一个字符串。
* @param list List
* @param delim String
* @return String
* @deprecated see combineList(list, delim)
*/
public static String combineStringList(List list, String delim) {
return combineList(list, delim);
}
/**
* 以指定的字符和长度生成一个该字符的指定长度的字符串。
* @param c 指定的字符
* @param length 指定的长度
* @return 最终生成的字符串
* @since 0.6
*/
public static String fillString( char c, int length) {
String ret = "" ;
for ( int i = 0 ; i < length; i ++ ) {
ret += c;
}
return ret;
}
/**
* 字符串数组中是否包含指定的字符串。
* @param strings 字符串数组
* @param string 字符串
* @param caseSensitive 是否大小写敏感
* @return 包含时返回true,否则返回false
* @since 0.4
*/
public static boolean contains(String[] strings, String string,
boolean caseSensitive) {
for ( int i = 0 ; i < strings.length; i ++ ) {
if (caseSensitive == true ) {
if (strings[i].equals(string)) {
return true ;
}
} else {
if (strings[i].equalsIgnoreCase(string)) {
return true ;
}
}
}
return false ;
}
/**
* 字符串数组中是否包含指定的字符串。大小写敏感。
* @param strings 字符串数组
* @param string 字符串
* @return 包含时返回true,否则返回false
* @since 0.4
*/
public static boolean contains(String[] strings, String string) {
return contains(strings, string, true );
}
/**
* 不区分大小写判定字符串数组中是否包含指定的字符串。
* @param strings 字符串数组
* @param string 字符串
* @return 包含时返回true,否则返回false
* @since 0.4
*/
public static boolean containsIgnoreCase(String[] strings, String string) {
return contains(strings, string, false );
}
/**
* 得到字符串的字节长度
* @param source 字符串
* @return 字符串的字节长度
* @since 0.6
*/
public static int getByteLength(String source) {
int len = 0 ;
for ( int i = 0 ; i < source.length(); i ++ ) {
char c = source.charAt(i);
int highByte = c >>> 8 ;
len += highByte == 0 ? 1 : 2 ;
}
return len;
}
/**
* 判断字符是否为双字节字符,如中文
* @param c char
* @return boolean
*/
public static boolean isDoubleByte( char c) {
return ! ( (c >>> 8 ) == 0 );
}
/**
* 输出固定字节长度的字符串
* @param source String
* @param len int
* @param exChar String
* @param exStr String
* @return String
*/
public static String getSubStr(String source, int len, String exChar,
String exStr) {
if (source == null || getByteLength(source) <= len) {
return source;
}
StringBuffer result = new StringBuffer();
char c = ' \u0000 ' ;
int i = 0 , j = 0 ;
for (; i < len; j ++ ) {
result.append(c);
c = source.charAt(j);
i += isDoubleByte(c) ? 2 : 1 ;
}
/**
* 到这里i有两种情况:等于len或是len+1,如果是len+1,说明是双字节,并多出一个字节
* 这时候就只能append(exChar),否则就append(c)
*/
if (i > len) {
result.append(exChar);
} else {
result.append(c);
}
result.append(exStr);
return result.toString();
}
public static String getSubStr(String source, int len) {
return getSubStr(source, len, " . " , " " );
}
/**
* 判断输入参数是否为null返回一个非null的值
* @param s String 判断的值
* @return String
*/
public static String getNotNullStr(String s) {
return (s == null ) ? "" : s.trim();
}
/**
* 返回一个十进制的整数
* @param s String 要转换为整数的字符串
* @param defaultValue int 当s不为整数时返回的默认值
* @return int
* @deprecated
* @see NumberUtil
*/
public static int parseInt(String s, int defaultValue) {
int rt = defaultValue;
try {
rt = Integer.parseInt(s);
} catch (NumberFormatException e) {
rt = defaultValue;
}
return rt;
}
/**
* 转换输入的字符串为一十进制整数
* @param s String
* @return int 如果转换不成功,则返回0
* @deprecated
* @see NumberUtil
*/
public static int parseInt(String s) {
return NumberUtil.parseInt(s, 0 );
}
/**
* 返回一个十进制长整数
* @param s String 要转换为长整数的字符串
* @param defaultValue long 当s不为整数时返回的默认值
* @return int
* @deprecated
* @see NumberUtil
*/
public static long parseLong(String s, long defaultValue) {
long rt = defaultValue;
try {
rt = Long.parseLong(s);
} catch (NumberFormatException e) {
rt = defaultValue;
}
return rt;
}
/**
* 返回一个十进制长整数
* @param s 要转换为长整数的字符串
* @return 当s不为整数时返回0
* @deprecated
* @see NumberUtil
*/
public static long parseLong(String s) {
return parseLong(s, 0 );
}
/**
* 返回一个整数数组
* @param s String[]
* @return int[]
* @deprecated
* @see NumberUtil
*/
public static int [] parseInt(String[] s){
if (s == null ) {
return ( new int [ 0 ]);
}
int [] result = new int [s.length];
try {
for ( int i = 0 ; i < s.length; i ++ ) {
result[i] = Integer.parseInt(s[i]);
}
} catch (NumberFormatException ex) {
}
return result;
}
/**
* 将字符串的第一个字母大写
* @param s String
* @return String
*/
public static String firstCharToUpperCase(String s) {
if (s == null || s.length() < 1 ) {
return "" ;
}
char [] arrC = s.toCharArray();
arrC[ 0 ] = Character.toUpperCase(arrC[ 0 ]);
return String.copyValueOf(arrC);
/*
char c = s.charAt(0);
c = Character.toUpperCase(c);
return Character.toString(c) + s.substring(1);
*/
}
/**
* 根据当前字节长度取出加上当前字节长度不超过最大字节长度的子串
* @param str
* @param currentLen
* @param MAX_LEN
* @return
*/
public static String getSubStr(String str, int currentLen, int MAX_LEN){
int i;
for (i = 0 ; i < str.length(); i ++ ){
if ( str.substring( 0 , i + 1 ).getBytes().length + currentLen > MAX_LEN){
break ;
}
}
if (i == 0 ){
return "" ;
} else {
return str.substring( 0 ,i);
}
}
private static String[] arrAntiKeys = new String[]{ " 抗日 " , " 日货 " , " 游行 " , " 示威 " , " 抗议 " , " 钓鱼岛 " , " 法轮 " , " 网络警察 " , " WWTTJJLL " };
/**
* 关键字替换成??
* @param keys
* @param arg
* @return
*/
public static String replaceByKeys(String[] keys,String arg){
String sbf = arg;
String[] getarrAntiKeys = arrAntiKeys;
if ((keys != null ) && (keys.length > 0 )) getarrAntiKeys = keys;
for ( int i = 0 ;i < getarrAntiKeys.length;i ++ ){
sbf = sbf.replaceAll(getarrAntiKeys[i], " ?? " );
}
return sbf;
}
/**
* 关键字删除
* @param parm
* @return
*/
public static String unicodeReplDel(String parm){
int area1min = 9601 ;
int area1max = 9794 ;
int area2min = 12288 ;
int area2max = 12311 ;
StringBuffer result = new StringBuffer( "" );
if (parm.trim().length() > 0 ){
for ( int i = 0 ; i < parm.length() ; i ++ ){
char c = parm.charAt(i);
if ( ! ((( int )c >= area1min && ( int )c <= area1max) || (( int )c >= area2min && ( int )c <= area2max))){
result.append(c);
}
}
}
return result.toString();
}
/**
* 将电话号码及邮件地址关键字替换成xx
* @param parm String
* @return String
*/
public static String checkStr(String parm){
String sbf = parm;
String destsbf = sbf;
String tempstr = "" ;
Pattern pattern;
Matcher matcher;
Vector regxs = new Vector();
regxs.add( " ([00零]{0,1}(([0-90123456789零壹贰参肆伍陆柒捌玖一二三四五六七八九]{3})|(10)|(21)|(22)|(23)|(24)|(25)|(26)|(27)|(28)|(29)|(壹零)|(贰壹)|(贰贰)|(贰参)|(贰肆)|(贰伍)|(贰陆)|(贰柒)|(贰捌)|(贰玖)|(一(0|0))|(二一)|(二二)|(二三)|(二四)|(二五)|(二六)|(二七)|(二八)|(二九))[ ]{0,}[\\)\\)]{0,}[ ]{0,}([--]{1}|[ ]{0,})[ ]{0,}[0-90123456789零壹贰参肆伍陆柒捌玖一二三四五六七八九 ]{6,}[0-90123456789零壹贰参肆伍陆柒捌玖一二三四五六七八九]{1})|([零壹贰参肆伍陆柒捌玖一二三四五六七八九 ]{6,}[零壹贰参肆伍陆柒捌玖一二三四五六七八九]{1}) " );
regxs.add( " [11壹一]{1}[33参三]{1}[0-90123456789零壹贰参肆伍陆柒捌玖一二三四五六七八九 --]{7,}[0-90123456789零壹贰参肆伍陆柒捌玖一二三四五六七八九]{2} " );
regxs.add( " [A-Za-zA-Za-z0-9_0123456789]+([-+.][A-Za-zA-Za-z0-9_0123456789]+)*((@)|(@))[A-Za-zA-Za-z0-9_0123456789]+([-.][A-Za-zA-Za-z0-9_0123456789]+)*((\\.)|(。)|(.))[A-Za-zA-Za-z0-9_0123456789]+([-.][A-Za-zA-Za-z0-9_0123456789]+)* " );
for ( int i = 0 ;i <= regxs.size() - 2 ;i ++ ){
pattern = Pattern.compile((String)regxs.get(i));
matcher = pattern.matcher(sbf);
while (matcher.find()){
tempstr = matcher.group();
if ((tempstr.indexOf( " ) " ) > 0 ) || (tempstr.indexOf( " ) " ) > 0 )){
if (tempstr.indexOf( " ) " ) > 0 ){
tempstr = tempstr.substring( 0 ,tempstr.indexOf( " ) " )) + " \\ " + tempstr.substring(tempstr.indexOf( " ) " ));
}
if (tempstr.indexOf( " ) " ) > 0 ){
tempstr = tempstr.substring( 0 ,tempstr.indexOf( " ) " )) + " \\ " + tempstr.substring(tempstr.indexOf( " ) " ));
}
Pattern secpattern;
Matcher secmatcher;
secpattern = Pattern.compile(tempstr);
secmatcher = secpattern.matcher(destsbf);
destsbf = secmatcher.replaceFirst(tempstr.substring( 0 ,tempstr.length() - 2 ) + " " );
} else
destsbf = destsbf.replaceFirst(tempstr,tempstr.substring( 0 ,tempstr.length() - 2 ) + " " );
}
}
int ipos =- 1 ;
pattern = Pattern.compile((String)regxs.get( 2 ));
matcher = pattern.matcher(sbf);
while (matcher.find()){
tempstr = matcher.group();
if (tempstr.indexOf( " @ " ) > 0 )
ipos = tempstr.indexOf( " @ " );
else
ipos = tempstr.indexOf( " @ " );
destsbf = destsbf.replaceFirst(tempstr, " " + tempstr.substring(ipos));
}
return destsbf;
}
}
import java.util. * ;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.StringCharacterIterator;
public class StringUtil {
// private StringUtil(){}
/**
* 将一个字串的首字母大写
* @param s String 源字串
* @return String 首字母大写后的字串
*/
public static String toUpperCaseFirstLetter(String s) {
return isNullStr(s)
? s
: s.substring( 0 , 1 ).toUpperCase() + s.substring( 1 );
}
/**
* 把空字符串转换为empty
* @param s
* @return
* @deprecated
* @see getNotNullStr
*/
public static final String nullToEmptyOfStr(String s) {
if (s != null )
return s.trim();
else
return "" ;
}
/**
*
* @param s
* @return
*/
public static final String escapeErrorChar(String s) {
String s1 = null ;
s1 = s;
if (s1 == null ) {
return s1;
} else {
s1 = replace(s1, " \\ " , " \\\\ " );
s1 = replace(s1, " \ "" , " \\\ "" );
return s1;
}
}
/**
* 取指定字符串的指定长度子字串
* @param strAll
* @param strLen
* @return
*/
public static final String subStr(String strAll, int strLen) {
String strNew = nullToEmptyOfStr(strAll);
String myStr = "" ;
if (strNew.length() >= strLen) {
myStr = strNew.substring( 0 , strLen);
} else {
myStr = strNew;
}
return myStr;
}
/*
public static final String streamToString(InputStream in)
{
StringBuffer sb=new StringBuffer("");
byte[] buffer = new byte[4096];
int bytes_read;
try
{
while ( (bytes_read = in.read(buffer)) != -1)
{
sb.append(new String(buffer, 0, bytes_read, "GBK"));
}
return sb.toString();
}
catch(Exception ex)
{
return null;
}
}
*/
public static final String replaceIgnoreCase(
String s,
String s1,
String s2) {
if (s == null )
return null ;
String s3 = s.toLowerCase();
String s4 = s1.toLowerCase();
int i = 0 ;
if ((i = s3.indexOf(s4, i)) >= 0 ) {
char ac[] = s.toCharArray();
char ac1[] = s2.toCharArray();
int j = s1.length();
StringBuffer stringbuffer = new StringBuffer(ac.length);
stringbuffer.append(ac, 0 , i).append(ac1);
i += j;
int k;
for (k = i;(i = s3.indexOf(s4, i)) > 0 ; k = i) {
stringbuffer.append(ac, k, i - k).append(ac1);
i += j;
}
stringbuffer.append(ac, k, ac.length - k);
return stringbuffer.toString();
} else {
return s;
}
}
public static final String formatInputStr(String s) {
String s1 = s;
s1 = nullToEmptyOfStr(s1);
s1 = escapeHTMLTags(s1);
return s1;
}
public static final String escapeHTMLTags(String s) {
if (s == null || s.length() == 0 )
return s;
StringBuffer stringbuffer = new StringBuffer(s.length());
byte byte0 = 32 ;
for ( int i = 0 ; i < s.length(); i ++ ) {
char c = s.charAt(i);
if (c == ' < ' )
stringbuffer.append( " < " );
else if (c == ' > ' )
stringbuffer.append( " > " );
else
stringbuffer.append(c);
}
return stringbuffer.toString();
}
// 字符串替换 s 搜索字符串 s1 要查找字符串 s2 要替换字符串
public static String replace(String s, String s1, String s2) {
if (s == null )
return null ;
int i = 0 ;
if ((i = s.indexOf(s1, i)) >= 0 ) {
char ac[] = s.toCharArray();
char ac1[] = s2.toCharArray();
int j = s1.length();
StringBuffer stringbuffer = new StringBuffer(ac.length);
stringbuffer.append(ac, 0 , i).append(ac1);
i += j;
int k;
for (k = i;(i = s.indexOf(s1, i)) > 0 ; k = i) {
stringbuffer.append(ac, k, i - k).append(ac1);
i += j;
}
stringbuffer.append(ac, k, ac.length - k);
return stringbuffer.toString();
} else {
return s;
}
}
public static String replace(String s, String s1, String s2, int ai[]) {
if (s == null )
return null ;
int i = 0 ;
if ((i = s.indexOf(s1, i)) >= 0 ) {
int j = 0 ;
j ++ ;
char ac[] = s.toCharArray();
char ac1[] = s2.toCharArray();
int k = s1.length();
StringBuffer stringbuffer = new StringBuffer(ac.length);
stringbuffer.append(ac, 0 , i).append(ac1);
i += k;
int l;
for (l = i;(i = s.indexOf(s1, i)) > 0 ; l = i) {
j ++ ;
stringbuffer.append(ac, l, i - l).append(ac1);
i += k;
}
stringbuffer.append(ac, l, ac.length - l);
ai[ 0 ] = j;
return stringbuffer.toString();
} else {
return s;
}
}
// 把字符串转换为向量
public static Vector splite(String s, String s1) {
Vector vector = new Vector();
Object obj = null ;
Object obj1 = null ;
boolean flag = false ;
int i;
for (; s.length() >= 0 ; s = s.substring(i + s1.length(), s.length())) {
i = s.indexOf(s1);
if (i < 0 ) {
vector.addElement(s);
break ;
}
String s2 = s.substring( 0 , i);
vector.addElement(s2);
}
return vector;
}
/**
* convert Array to ArrayList
* @param sz String[]
* @param len int
* @return ArrayList
*/
public static ArrayList getArrayListFromArray(String[] sz, int len) {
ArrayList aTmp = new ArrayList();
if (isNullStr(sz)) {
for ( int i = 0 ; i < len; i ++ ) {
aTmp.add( "" );
}
} else {
for ( int i = 0 ; i < sz.length; i ++ ) {
aTmp.add(sz[i]);
}
}
return aTmp;
}
/**
* Convert to int Base200312291149
* @param o Object
* @return int
*/
public static int cNum(Object o) {
try {
return Integer.parseInt(cStr(o));
} catch (Exception ex) {
return 0 ;
}
}
/**
* Convert to String from object Base200312291148
* @param o Object
* @return String
*/
public static String cStr(Object o) {
return o == null ? "" : o.toString();
}
/**
* 判断此字符串是否为空、空字符串,或"null"
* @param str
* @return
*/
public static boolean isNullStr(String s) {
return (s == null || s.equals( " null " ) || s.equals( "" )) ? true : false ;
}
/**
* 如果字符串为空、空字符串,或"null"时返回"0"
* @param str
* @return String
*/
public static String emptyToZero(String str) {
if (isNullStr(str))
return " 0 " ;
else
return str.trim();
}
/**
* 判断此字符串是否为空、空字符串,或"null"
* @param str
* @return
*/
public static boolean isNullStr(Object o) {
return (
o == null
|| o.toString().equals( " null " )
|| o.toString().equals( "" ))
?
// return (o==null||o.toString().equals(""))?
true : false ;
}
/**
* 如果字符串str为空则转换为str1
* @param str
* @param str1
* @return
*/
public static String getNullStr(String str, String str1) {
if (isNullStr(str))
return str1;
else
return str;
}
/**
* 将字符串str转换为GBK编码格式
* @param str
* @return
*/
public static String getGBKStr(String str) {
try {
String temp_p;
temp_p = str;
// temp_p = getNullStr(temp_p, "");
temp_p = nullToEmptyOfStr(temp_p);
byte [] temp_t = temp_p.getBytes( " ISO8859_1 " );
String temp = new String(temp_t, " GBK " );
return temp;
} catch (Exception e) {
return "" ;
}
}
public static String getISOStr(String str) {
try {
String temp_p;
temp_p = str;
temp_p = getNullStr(temp_p, "" );
byte [] temp_t = temp_p.getBytes( " ISO8859_1 " );
String temp = new String(temp_t);
return temp;
} catch (Exception e) {}
return " null " ;
}
/**
* 中文转换--文章换行的转换
* @param str
* @return
*/
public static String getText(String str) {
if (str == null )
return ( "" );
if (str.equals( "" ))
return ( "" );
// 建立一个StringBuffer来处理输入数据
StringBuffer buf = new StringBuffer(str.length() + 6 );
char ch = ' \n ' ;
for ( int i = 0 ; i < str.length(); i ++ ) {
ch = str.charAt(i);
if (ch == ' \n ' ) {
buf.append( " <br> " );
} else if (ch == ' \t ' ) {
buf.append( " " );
} else if (ch == ' ' ) {
buf.append( " " );
} else {
buf.append(ch);
}
}
return buf.toString();
}
/**
* 格式化复选框生成字串
* @param selectID
* @return
* @deprecated
* @see this.combineArray(String[] array)
*/
public static String getCheckbox(String[] selectID) {
String[] ss;
ss = selectID;
String temp = "" ;
try {
for ( int i = 0 ; i < ss.length; i ++ )
temp += ss[i] + " , " ;
if (temp.length() > 0 )
temp = temp.substring( 0 , temp.length() - 1 );
return temp;
} catch (NullPointerException e) {
return "" ;
}
}
/**
* 将字串转成日期,字串格式: yyyy/MM/dd
* @author Base200312111725
* @param string String
* @return Date
*/
public static Date toDate(String string) {
try {
DateFormat formatter = new SimpleDateFormat( " yyyy/MM/dd " );
return (Date) formatter.parse(string);
} catch (Exception ex) {
System.err.println(
" [ com.huanglq.util.StringUtil.toDate(string) ] "
+ ex.getMessage());
return null ;
}
}
/**
* 将字串转成日期和时间,字串格式: yyyy/MM/dd HH:mm:ss
* @author Base200312111726
* @param string String
* @return Date
*/
public static Date toDatetime(String string) {
try {
DateFormat formatter = new SimpleDateFormat( " yyyy/MM/dd HH:mm:ss " );
return (Date) formatter.parse(string);
} catch (Exception ex) {
System.err.println(
" [ com.huanglq.util.StringUtil.toDatetime(string) ] "
+ ex.getMessage());
return null ;
}
}
/**
* 判断单选框是否选中
* @author tempnc20031222
* @param inparam
* @param val
* @return 是否选中
*/
public static String isChecked(String inparam, String val) {
try {
if (inparam.trim().equals(val.trim()))
return " checked " ;
else
return "" ;
} catch (Exception ex) {
System.err.println(
" [ com.huanglq.util.StringUtil.toDatetime(string) ] "
+ ex.getMessage());
return null ;
}
}
public static void main(String[] argv) {
// StringUtil su = new StringUtil();
/*
System.out.println(
":" + StringUtil.toUpperCaseFirstLetter(""));
*/
String strTest = " 具备的资格:\n " +
" - 高级经理岗位资格证书(No.A100xxx),上海市人事局 \n " +
" - 科技管理专业高级工程师任职资格证书(No.01C4050xxx/1077xxx),上海市政府人事局 \n " +
" - ISO9000 执照 上海质量管理协会 \n " +
" - 原产地证书(No.960xxx/37xx),中国国际贸易促进委员会(CCPIT)上海市分会 \n " +
" - 中国通信学会有线传输专业委员会会员(No.31xx) \n " +
" - 上海化学化工学会高分子专业委员会会员(No.9-71xx) \n " +
" - 上海塑料工程学会塑料加工专业委员会会员 \n " +
" - 联系方式:手机/137 0168 8348石晓东, 电话及传真/(21)6433 8067石晓东, Email: [email protected], [email protected] \n " +
" - 联系方式:mail:[email protected] \n " +
" 传真/(21)6433 8067石晓东 " +
" 手机:137-2557-6014\n " ;
System.out.println(checkStr(strTest));
}
/**
* 根据转义列表对字符串进行转义(escape)。
* @param source 待转义的字符串
* @param escapeCharMap 转义列表
* @return 转义后的字符串
*/
public static String escapeCharacter(
String source,
HashMap escapeCharMap) {
if (source == null || source.length() == 0 ) {
return source;
}
if (escapeCharMap.size() == 0 ) {
return source;
}
StringBuffer sb = new StringBuffer(source.length() + 100 );
StringCharacterIterator sci = new StringCharacterIterator(source);
for ( char c = sci.first();
c != StringCharacterIterator.DONE;
c = sci.next()) {
String character = String.valueOf(c);
if (escapeCharMap.containsKey(character)) {
character = (String) escapeCharMap.get(character);
}
sb.append(character);
}
return sb.toString();
}
/**
* 此方法将给出的字符串source使用delim划分为单词数组。
* @param source 需要进行划分的原字符串
* @param delim 单词的分隔字符串
* @return 划分以后的数组,如果source为null的时候返回以source为唯一元素的数组,
* 如果delim为null则使用逗号作为分隔字符串。
* @since 0.1
*/
public static String[] split(String source, String delim) {
String[] wordLists;
if (source == null ) {
wordLists = new String[ 1 ];
wordLists[ 0 ] = source;
return wordLists;
}
if (delim == null ) {
delim = " , " ;
}
StringTokenizer st = new StringTokenizer(source, delim);
int total = st.countTokens();
wordLists = new String[total];
for ( int i = 0 ; i < total; i ++ ) {
wordLists[i] = st.nextToken();
}
return wordLists;
}
/**
* 此方法将给出的字符串source使用delim划分为单词数组。
* @param source 需要进行划分的原字符串
* @param delim 单词的分隔字符
* @return 划分以后的数组,如果source为null的时候返回以source为唯一元素的数组。
* @since 0.2
*/
public static String[] split(String source, char delim) {
return split(source, String.valueOf(delim));
}
/**
* 此方法将给出的字符串source使用逗号划分为单词数组。
* @param source 需要进行划分的原字符串
* @return 划分以后的数组,如果source为null的时候返回以source为唯一元素的数组。
* @since 0.1
*/
public static String[] split(String source) {
return split(source, " , " );
}
/**
* 将set的所有记录并成一个以 delim 分隔的字符串
* @param set
* @param delim
* @return
*/
public static String combine(Set set, String delim) {
if (set == null || set.size() == 0 ) {
return "" ;
}
if (delim == null ) {
delim = "" ;
}
StringBuffer sb = new StringBuffer( 100 );
for (Iterator iter = set.iterator(); iter.hasNext(); ) {
sb.append(iter.next());
sb.append(delim);
}
if (sb.length() >= delim.length()) {
sb.delete(sb.length() - 1 - delim.length(), sb.length() - 1 );
}
return sb.toString();
}
/**
* 将set的所有记录并成一个以 , 分隔的字符串
* @param set
* @param delim
* @return
*/
public static String combine(Set set) {
return combine(set, " , " );
}
/**
* 将字符串数组合并成一个以 delim 分隔的字符串
* @param array 字符串数组
* @param delim 分隔符,为null的时候使用""作为分隔符(即没有分隔符)
* @return 合并后的字符串
*/
public static String combineArray(String[] array, String delim) {
if (array == null || array.length == 0 ) {
return "" ;
}
int length = array.length - 1 ;
if (delim == null ) {
delim = "" ;
}
StringBuffer result = new StringBuffer(length * 8 );
for ( int i = 0 ; i < length; i ++ ) {
result.append(array[i]);
result.append(delim);
}
result.append(array[length]);
return result.toString();
}
/**
* 将字符串数组合并成一个以,号分隔的字符串
* @param array 字符串数组
* @return 合并后的字符串
*/
public static String combineArray(String[] array) {
return combineArray(array, " , " );
}
/**
* 将字符串数组使用指定的分隔符合并成一个字符串。
* @param array 字符串数组
* @param delim 分隔符,为null的时候使用""作为分隔符(即没有分隔符)
* @return 合并后的字符串
* @deprecated
*/
public static String combineStringArray(String[] array, String delim) {
return combineArray(array, delim);
}
/**
* 将int数组使用指定的分隔符合并成一个字符串
* @param array int[] int 数组
* @param delim String 分隔符,为null的时候使用""作为分隔符(即没有分隔符)
* @return String 合并后的字符串
*/
public static String combineArray( int [] array, String delim) {
if (array == null || array.length == 0 ) {
return "" ;
}
int length = array.length - 1 ;
if (delim == null ) {
delim = "" ;
}
StringBuffer result = new StringBuffer();
for ( int i = 0 ; i < length; i ++ ) {
result.append(Integer.toString(array[i]));
result.append(delim);
}
result.append(Integer.toString(array[length]));
return result.toString();
}
/**
* 将int数组合并成一个以,号分隔的字符串
* @param array 字符串数组
* @return 合并后的字符串
*/
public static String combineArray( int [] array) {
return combineArray(array, " , " );
}
/**
* 将字符串List使用指定的分隔符合并成一个字符串。
* @param list List
* @param delim String
* @return String
*/
public static String combineList(List list, String delim) {
if (list == null || list.size() == 0 ) {
return "" ;
} else {
StringBuffer result = new StringBuffer();
for ( int i = 0 ; i < list.size() - 1 ; i ++ ) {
result.append(list.get(i));
result.append(delim);
}
result.append(list.get(list.size() - 1 ));
return result.toString();
}
}
/**
* 将字符串List使用 , 合并成一个字符串。
* @param list List
* @return String
*/
public static String combineList(List list) {
return combineList(list, " , " );
}
/**
* 将字符串List使用指定的分隔符合并成一个字符串。
* @param list List
* @param delim String
* @return String
* @deprecated see combineList(list, delim)
*/
public static String combineStringList(List list, String delim) {
return combineList(list, delim);
}
/**
* 以指定的字符和长度生成一个该字符的指定长度的字符串。
* @param c 指定的字符
* @param length 指定的长度
* @return 最终生成的字符串
* @since 0.6
*/
public static String fillString( char c, int length) {
String ret = "" ;
for ( int i = 0 ; i < length; i ++ ) {
ret += c;
}
return ret;
}
/**
* 字符串数组中是否包含指定的字符串。
* @param strings 字符串数组
* @param string 字符串
* @param caseSensitive 是否大小写敏感
* @return 包含时返回true,否则返回false
* @since 0.4
*/
public static boolean contains(String[] strings, String string,
boolean caseSensitive) {
for ( int i = 0 ; i < strings.length; i ++ ) {
if (caseSensitive == true ) {
if (strings[i].equals(string)) {
return true ;
}
} else {
if (strings[i].equalsIgnoreCase(string)) {
return true ;
}
}
}
return false ;
}
/**
* 字符串数组中是否包含指定的字符串。大小写敏感。
* @param strings 字符串数组
* @param string 字符串
* @return 包含时返回true,否则返回false
* @since 0.4
*/
public static boolean contains(String[] strings, String string) {
return contains(strings, string, true );
}
/**
* 不区分大小写判定字符串数组中是否包含指定的字符串。
* @param strings 字符串数组
* @param string 字符串
* @return 包含时返回true,否则返回false
* @since 0.4
*/
public static boolean containsIgnoreCase(String[] strings, String string) {
return contains(strings, string, false );
}
/**
* 得到字符串的字节长度
* @param source 字符串
* @return 字符串的字节长度
* @since 0.6
*/
public static int getByteLength(String source) {
int len = 0 ;
for ( int i = 0 ; i < source.length(); i ++ ) {
char c = source.charAt(i);
int highByte = c >>> 8 ;
len += highByte == 0 ? 1 : 2 ;
}
return len;
}
/**
* 判断字符是否为双字节字符,如中文
* @param c char
* @return boolean
*/
public static boolean isDoubleByte( char c) {
return ! ( (c >>> 8 ) == 0 );
}
/**
* 输出固定字节长度的字符串
* @param source String
* @param len int
* @param exChar String
* @param exStr String
* @return String
*/
public static String getSubStr(String source, int len, String exChar,
String exStr) {
if (source == null || getByteLength(source) <= len) {
return source;
}
StringBuffer result = new StringBuffer();
char c = ' \u0000 ' ;
int i = 0 , j = 0 ;
for (; i < len; j ++ ) {
result.append(c);
c = source.charAt(j);
i += isDoubleByte(c) ? 2 : 1 ;
}
/**
* 到这里i有两种情况:等于len或是len+1,如果是len+1,说明是双字节,并多出一个字节
* 这时候就只能append(exChar),否则就append(c)
*/
if (i > len) {
result.append(exChar);
} else {
result.append(c);
}
result.append(exStr);
return result.toString();
}
public static String getSubStr(String source, int len) {
return getSubStr(source, len, " . " , " " );
}
/**
* 判断输入参数是否为null返回一个非null的值
* @param s String 判断的值
* @return String
*/
public static String getNotNullStr(String s) {
return (s == null ) ? "" : s.trim();
}
/**
* 返回一个十进制的整数
* @param s String 要转换为整数的字符串
* @param defaultValue int 当s不为整数时返回的默认值
* @return int
* @deprecated
* @see NumberUtil
*/
public static int parseInt(String s, int defaultValue) {
int rt = defaultValue;
try {
rt = Integer.parseInt(s);
} catch (NumberFormatException e) {
rt = defaultValue;
}
return rt;
}
/**
* 转换输入的字符串为一十进制整数
* @param s String
* @return int 如果转换不成功,则返回0
* @deprecated
* @see NumberUtil
*/
public static int parseInt(String s) {
return NumberUtil.parseInt(s, 0 );
}
/**
* 返回一个十进制长整数
* @param s String 要转换为长整数的字符串
* @param defaultValue long 当s不为整数时返回的默认值
* @return int
* @deprecated
* @see NumberUtil
*/
public static long parseLong(String s, long defaultValue) {
long rt = defaultValue;
try {
rt = Long.parseLong(s);
} catch (NumberFormatException e) {
rt = defaultValue;
}
return rt;
}
/**
* 返回一个十进制长整数
* @param s 要转换为长整数的字符串
* @return 当s不为整数时返回0
* @deprecated
* @see NumberUtil
*/
public static long parseLong(String s) {
return parseLong(s, 0 );
}
/**
* 返回一个整数数组
* @param s String[]
* @return int[]
* @deprecated
* @see NumberUtil
*/
public static int [] parseInt(String[] s){
if (s == null ) {
return ( new int [ 0 ]);
}
int [] result = new int [s.length];
try {
for ( int i = 0 ; i < s.length; i ++ ) {
result[i] = Integer.parseInt(s[i]);
}
} catch (NumberFormatException ex) {
}
return result;
}
/**
* 将字符串的第一个字母大写
* @param s String
* @return String
*/
public static String firstCharToUpperCase(String s) {
if (s == null || s.length() < 1 ) {
return "" ;
}
char [] arrC = s.toCharArray();
arrC[ 0 ] = Character.toUpperCase(arrC[ 0 ]);
return String.copyValueOf(arrC);
/*
char c = s.charAt(0);
c = Character.toUpperCase(c);
return Character.toString(c) + s.substring(1);
*/
}
/**
* 根据当前字节长度取出加上当前字节长度不超过最大字节长度的子串
* @param str
* @param currentLen
* @param MAX_LEN
* @return
*/
public static String getSubStr(String str, int currentLen, int MAX_LEN){
int i;
for (i = 0 ; i < str.length(); i ++ ){
if ( str.substring( 0 , i + 1 ).getBytes().length + currentLen > MAX_LEN){
break ;
}
}
if (i == 0 ){
return "" ;
} else {
return str.substring( 0 ,i);
}
}
private static String[] arrAntiKeys = new String[]{ " 抗日 " , " 日货 " , " 游行 " , " 示威 " , " 抗议 " , " 钓鱼岛 " , " 法轮 " , " 网络警察 " , " WWTTJJLL " };
/**
* 关键字替换成??
* @param keys
* @param arg
* @return
*/
public static String replaceByKeys(String[] keys,String arg){
String sbf = arg;
String[] getarrAntiKeys = arrAntiKeys;
if ((keys != null ) && (keys.length > 0 )) getarrAntiKeys = keys;
for ( int i = 0 ;i < getarrAntiKeys.length;i ++ ){
sbf = sbf.replaceAll(getarrAntiKeys[i], " ?? " );
}
return sbf;
}
/**
* 关键字删除
* @param parm
* @return
*/
public static String unicodeReplDel(String parm){
int area1min = 9601 ;
int area1max = 9794 ;
int area2min = 12288 ;
int area2max = 12311 ;
StringBuffer result = new StringBuffer( "" );
if (parm.trim().length() > 0 ){
for ( int i = 0 ; i < parm.length() ; i ++ ){
char c = parm.charAt(i);
if ( ! ((( int )c >= area1min && ( int )c <= area1max) || (( int )c >= area2min && ( int )c <= area2max))){
result.append(c);
}
}
}
return result.toString();
}
/**
* 将电话号码及邮件地址关键字替换成xx
* @param parm String
* @return String
*/
public static String checkStr(String parm){
String sbf = parm;
String destsbf = sbf;
String tempstr = "" ;
Pattern pattern;
Matcher matcher;
Vector regxs = new Vector();
regxs.add( " ([00零]{0,1}(([0-90123456789零壹贰参肆伍陆柒捌玖一二三四五六七八九]{3})|(10)|(21)|(22)|(23)|(24)|(25)|(26)|(27)|(28)|(29)|(壹零)|(贰壹)|(贰贰)|(贰参)|(贰肆)|(贰伍)|(贰陆)|(贰柒)|(贰捌)|(贰玖)|(一(0|0))|(二一)|(二二)|(二三)|(二四)|(二五)|(二六)|(二七)|(二八)|(二九))[ ]{0,}[\\)\\)]{0,}[ ]{0,}([--]{1}|[ ]{0,})[ ]{0,}[0-90123456789零壹贰参肆伍陆柒捌玖一二三四五六七八九 ]{6,}[0-90123456789零壹贰参肆伍陆柒捌玖一二三四五六七八九]{1})|([零壹贰参肆伍陆柒捌玖一二三四五六七八九 ]{6,}[零壹贰参肆伍陆柒捌玖一二三四五六七八九]{1}) " );
regxs.add( " [11壹一]{1}[33参三]{1}[0-90123456789零壹贰参肆伍陆柒捌玖一二三四五六七八九 --]{7,}[0-90123456789零壹贰参肆伍陆柒捌玖一二三四五六七八九]{2} " );
regxs.add( " [A-Za-zA-Za-z0-9_0123456789]+([-+.][A-Za-zA-Za-z0-9_0123456789]+)*((@)|(@))[A-Za-zA-Za-z0-9_0123456789]+([-.][A-Za-zA-Za-z0-9_0123456789]+)*((\\.)|(。)|(.))[A-Za-zA-Za-z0-9_0123456789]+([-.][A-Za-zA-Za-z0-9_0123456789]+)* " );
for ( int i = 0 ;i <= regxs.size() - 2 ;i ++ ){
pattern = Pattern.compile((String)regxs.get(i));
matcher = pattern.matcher(sbf);
while (matcher.find()){
tempstr = matcher.group();
if ((tempstr.indexOf( " ) " ) > 0 ) || (tempstr.indexOf( " ) " ) > 0 )){
if (tempstr.indexOf( " ) " ) > 0 ){
tempstr = tempstr.substring( 0 ,tempstr.indexOf( " ) " )) + " \\ " + tempstr.substring(tempstr.indexOf( " ) " ));
}
if (tempstr.indexOf( " ) " ) > 0 ){
tempstr = tempstr.substring( 0 ,tempstr.indexOf( " ) " )) + " \\ " + tempstr.substring(tempstr.indexOf( " ) " ));
}
Pattern secpattern;
Matcher secmatcher;
secpattern = Pattern.compile(tempstr);
secmatcher = secpattern.matcher(destsbf);
destsbf = secmatcher.replaceFirst(tempstr.substring( 0 ,tempstr.length() - 2 ) + " " );
} else
destsbf = destsbf.replaceFirst(tempstr,tempstr.substring( 0 ,tempstr.length() - 2 ) + " " );
}
}
int ipos =- 1 ;
pattern = Pattern.compile((String)regxs.get( 2 ));
matcher = pattern.matcher(sbf);
while (matcher.find()){
tempstr = matcher.group();
if (tempstr.indexOf( " @ " ) > 0 )
ipos = tempstr.indexOf( " @ " );
else
ipos = tempstr.indexOf( " @ " );
destsbf = destsbf.replaceFirst(tempstr, " " + tempstr.substring(ipos));
}
return destsbf;
}
}
柴油发电机
发电机
柴油机
柴油发电机
13636374743(上海)
13291526067(嘉兴)