package com.sun.util;
import java.io.file;
import java.io.unsupportedencodingexception;
import java.net.urldecoder;
import java.net.urlencoder;
import java.security.messagedigest;
import java.sql.timestamp;
import java.text.numberformat;
import java.text.simpledateformat;
import java.util.date;
import java.util.regex.matcher;
import java.util.regex.pattern;
/**
* 字符串操作通用类
*
* @author sunjun
* @version v5.0
*/
public class stringutil {
// 字符串常量枚举
public static enum regex_enum {
email("^\\w ([- .']\\w )*@\\w ([-.]\\w )*\\.\\w ([-.]\\w )*$"), chinese_character(
"[\\u4e00-\\u9fa5] ");
private string value;
private regex_enum(string value) {
this.value = value;
}
public string tostring() {
return this.value;
}
};
/**
* 检查字符串str是否匹配正则表达式regex
*
* @param regex
* @param str
* @return
*/
public static boolean matcherregex(string regex, string str) {
pattern pattern = pattern.compile(regex);
matcher matcher = pattern.matcher(str);
return matcher.matches();
}
/**
* 是否为汉字
*
* @param ch
* @return
*/
public static boolean ischinesecharacter(char ch) {
return matcherregex(regex_enum.chinese_character.tostring(), string
.valueof(ch));
}
/**
* 按字节截取字符串
*
* @param str
* 要截取的字符串
* @param bytelength
* 长度
* @return 结果字符串
*/
public static string substring(string str, int bytelength) {
if (isblank(str))
return "";
if (str.getbytes().length <= bytelength)
return str;
if (str.length() >= bytelength)
str = str.substring(0, bytelength);
int readlen = 0;
string c = null;
stringbuffer sb = new stringbuffer("");
for (int i = 0; i < str.length(); i ) {
c = string.valueof(str.charat(i));
readlen = c.getbytes().length;
if (readlen > bytelength)
return sb.tostring();
sb.append(c);
}
return sb.tostring();
}
/**
* 检查字符串长度是否在指定长度范围内(minlength<=str.length<=maxlength)
*
* @param str
* 要检查的字符串
* @param minlength
* 最小长度
* @param maxlength
* 最大长度
* @return boolean 字符串长度在指定长度范围内返回true,否则返回false
*/
public static boolean checklength(string str, int minlength, int maxlength) {
if (isblank(str))
return false;
int len = str.length();
if (minlength == 0)
return len <= maxlength;
else if (maxlength == 0)
return len >= minlength;
else
return (len >= minlength && len <= maxlength);
}
/**
* 按utf-8编码来解码字符串
*
* @param str
* 要解码的字符串
* @return string 解码str后字符串
*/
public static string decodestring(string str) {
return decodestring(str, "utf-8");
}
/**
* 按指定编码来解码字符串
*
* @param str
* @param encoding
* @return
*/
public static string decodestring(string str, string encoding) {
if (isblank(str))
return "";
try {
return urldecoder.decode(str.trim(), encoding);
} catch (unsupportedencodingexception e) {
}
return "";
}
/**
* 按指定编码来解码字符串
*
* @param str
* @param encoding
* @return
*/
public static string decodeuri(string str) {
if (isblank(str))
return "";
try {
return new string(str.getbytes("iso8859-1"), "utf-8");
} catch (unsupportedencodingexception e) {
}
return "";
}
/**
* 按utf-8编码来编码字符串
*
* @param str
* 要编码的字符串
* @return string 编码str后字符串
*/
public static string encodestring(string str) {
return encodestring(str, "utf-8");
}
/**
* 按utf-8编码来编码字符串
*
* @param str
* 要编码的字符串
* @return string 编码str后字符串
*/
public static string encodestring(string str, string encoding) {
if (isblank(str))
return "";
try {
return urlencoder.encode(str.trim(), encoding);
} catch (unsupportedencodingexception e) {
}
return "";
}
/**
* 根据时间得到唯一字符串
*
* @return
*/
public static string getonlystring() {
return string.valueof(system.currenttimemillis());
}
/**
* 检查对象obj是否为空
*
* @param str
* 要检查的字符串
* @return boolean str为空返回true,否则返回false
*/
public static boolean isblank(object obj) {
if (obj == null)
return true;
if (obj instanceof string && obj.tostring().trim().length() == 0)
return true;
return false;
}
/**
* 检查字符串str是否为整型
*
* @param str
* 要检查的字符串
* @return boolean str为整型返回true,否则返回false
*/
public static boolean isinteger(string str) {
if (isblank(str))
return false;
try {
integer.parseint(str.trim());
return true;
} catch (exception e) {
}
return false;
}
/**
* 检查字符串str是否为长整型
*
* @param str
* 要检查的字符串
* @return boolean str为长整型返回true,否则返回false
*/
public static boolean islong(string str) {
if (isblank(str))
return false;
try {
long.parselong(str.trim());
return true;
} catch (exception e) {
}
return false;
}
/**
* 检查字符串str是否为布尔型
*
* @param str
* 要检查的字符串
* @return boolean str为布尔型返回true,否则返回false
*/
public static boolean isboolean(string str) {
if (isblank(str))
return false;
try {
boolean.parseboolean(str.trim());
return true;
} catch (exception e) {
}
return false;
}
/**
* 检查字符串str是否为double类型
*
* @param str
* @return
*/
public static boolean isdouble(string str) {
if (isblank(str))
return false;
try {
double.parsedouble(str.trim());
return true;
} catch (exception e) {
}
return false;
}
/**
* 检查字符串str是否为时间型
*
* @param str
* 要检查的字符串
* @return boolean str为时间型返回true,否则返回false
*/
public static boolean isdate(string str) {
if (isblank(str))
return false;
try {
java.sql.date sqldate = java.sql.date.valueof(str.trim());
return true;
} catch (exception e) {
}
return false;
}
/**
* 检查对象数组strings的每个元素是否为空
*
* @param objs
* 要检查的对象数组
* @return boolean objs数组元素为空返回true,否则返回false
*/
public static boolean isblanks(object... objs) {
for (object obj : objs) {
if (stringutil.isblank(obj))
return true;
}
return false;
}
/**
* 检查字符串数组str是否为长整型数组
*
* @param str
* 要检查的字符串
* @return boolean str为长整型数组返回true,否则返回false
*/
public static boolean islongs(string str[]) {
for (int i = 0; i < str.length; i ) {
if (!islong(str[i]))
return false;
}
return true;
}
/**
* 检查字符串数组str是否为整型数组
*
* @param str
* 要检查的字符串
* @return boolean str为整型数组返回true,否则返回false
*/
public static boolean isintegers(string str[]) {
for (int i = 0; i < str.length; i )
if (!isinteger(str[i]))
return false;
return true;
}
/**
* 检查字符串数组str是否为布尔型数组
*
* @param str
* 要检查的字符串
* @return boolean str为布尔型数组返回true,否则返回false
*/
public static boolean isbooleans(string str[]) {
for (int i = 0; i < str.length; i )
if (!isboolean(str[i]))
return false;
return true;
}
/**
* 检查字符串str是否为时间
*
* @param str
* 要检查的字符串
* @return str为时间型返回true,否则返回false
*/
public static boolean istimestamp(string str) {
if (isblank(str))
return false;
try {
java.sql.date d = java.sql.date.valueof(str.trim());
return true;
} catch (exception ex) {
}
return false;
}
/**
* 检查字符串str是否为(yyyy-mm-dd hh:mm:ss)模式的时间
*
* @param str
* 要检查的字符串
* @return str为时间型返回true,否则返回false
*/
public static boolean isfulltimestamp(string str) {
if (isblank(str))
return false;
try {
simpledateformat format = new simpledateformat(
"yyyy-mm-dd hh:mm:ss");
date date = format.parse(str.trim());
return date != null;
} catch (exception e) {
}
return false;
}
/**
* 将字符数组转换为长整型数组
*
* @param str
* 字符数组
* @return long[] 长整型数组
*/
public static long[] stringstolongs(string str[]) {
long lon[] = new long[str.length];
for (int i = 0; i < lon.length; i )
lon[i] = new long(str[i]);
return lon;
}
/**
* 将字符数组转换为整型数组
*
* @param str
* 字符数组
* @return integer[] 整型数组
*/
public static integer[] stringstointegers(string str[]) {
integer array[] = new integer[str.length];
for (int i = 0; i < array.length; i )
array[i] = new integer(str[i]);
return array;
}
/**
* 将字符数组转换为布尔型数组
*
* @param str
* 字符数组
* @return boolean[] 布尔型数组
*/
public static boolean[] stringstobooleans(string str[]) {
boolean array[] = new boolean[str.length];
for (int i = 0; i < array.length; i )
array[i] = new boolean(str[i]);
return array;
}
/**
* 将字符数组转换为浮点型数组
*
* @param str
* 字符数组
* @return double[] 浮点型数组
*/
public static double[] stringstodoubles(string str[]) {
double array[] = new double[str.length];
for (int i = 0; i < array.length; i )
array[i] = double.parsedouble(str[i]);
return array;
}
/**
* 根据指定时间和格式字符串得到时间格式字符串
*
* @param d
* 时间
* @param pattern
* 格式字符串
* @return string 时间格式字符串
*/
public static string formatdate(date d, string pattern) {
if (isblank(d))
return "";
simpledateformat format = new simpledateformat(
isblank(pattern) ? "yyyy-mm-dd hh-mm-ss" : pattern);
return format.format(d);
}
/**
* 根据时间字符串得到时间(yyyy-mm-dd)
*
* @param str
* 时间字符串
* @return timestamp 时间
*/
public static timestamp gettimestamp(string str) {
try {
date d = java.sql.date.valueof(str.trim());
return new timestamp(d.gettime());
} catch (exception ex) {
}
return null;
}
/**
* 根据时间字符串得到(yyyy-mm-dd hh-mm-ss)格式时间
*
* @param str
* 时间字符串
* @return timestamp 时间
*/
public static timestamp getfulltimestamp(string str) {
try {
simpledateformat format = new simpledateformat(
"yyyy-mm-dd hh:mm:ss");
date date = format.parse(str.trim());
return new timestamp(date.gettime());
} catch (exception ex) {
}
return null;
}
/**
* 得到数字格式化后的字符串
*
* @param number
* number类型
* @param minfractiondigits
* 小数最小位数
* @param maxfractiondigits
* 小数最大位数
* @return string 格式化后的字符串
*/
public static string formatnumber(number number, int minfractiondigits,
int maxfractiondigits) {
numberformat format = numberformat.getinstance();
format.setminimumfractiondigits(minfractiondigits);
format.setmaximumfractiondigits(maxfractiondigits);
return format.format(number);
}
/**
* 字符串高亮
* 解决了高亮前缀或高亮后缀在要高亮显示的字符串数组在存在时的问题,根据本算法可解决js高亮显示时相同的问题
*
* @param text
* 内容
* @param replacestrs
* 要高亮显示的字符串数组
* @param beginstr
* 高亮前缀,如
* @param endstr
* 高亮后缀,如
* @return
*/
public static string heightlight(string text, string[] replacestrs,
string beginstr, string endstr) {
if (text.length() == 0)
return text;
stringbuilder str = new stringbuilder();
for (int i = 0; i < replacestrs.length; i ) {
string replacestr = replacestrs[i];
int index = text.indexof(replacestr);
if (index >= 0) {
string afterstr = null;
if (index > 0) {
string beforestr = text.substring(0, index);
afterstr = text.substring(index replacestr.length());
str.append(heightlight(beforestr, replacestrs, beginstr,
endstr));
} else
afterstr = text.substring(replacestr.length());
str.append(beginstr).append(replacestr).append(endstr);
str
.append(heightlight(afterstr, replacestrs, beginstr,
endstr));
break;
}
}
if (str.length() == 0)
return text;
return str.tostring();
}
/**
* 替换指定的字符串数组为一个字符串
* 速度比string.replaceall快3倍左右,比apache-common stringutils.replace快2倍左右
*
* @param text
* @param replacestrs
* @param newstr
* @return
*/
public static string replaceall(string text, string[] replacestrs,
string newstr) {
if (text.length() == 0)
return text;
stringbuilder str = new stringbuilder();
for (int i = 0; i < replacestrs.length; i ) {
string replacestr = replacestrs[i];
int index = text.indexof(replacestr);
if (index >= 0) {
string afterstr = null;
if (index > 0) {
string beforestr = text.substring(0, index);
afterstr = text.substring(index replacestr.length());
str.append(replaceall(beforestr, replacestrs, newstr));
} else
afterstr = text.substring(replacestr.length());
str.append(newstr);
str.append(replaceall(afterstr, replacestrs, newstr));
break;
}
}
if (str.length() == 0)
return text;
return str.tostring();
}
/**
* 替换指定的字符串为一个字符串
* 速度比string.replaceall快3倍左右,比apache-common stringutils.replace快2倍左右
*
* @param text
* @param replacestr
* @param newstr
* @return
*/
public static string replaceall(string text, string replacestr,
string newstr) {
if (text.length() == 0)
return text;
stringbuilder str = new stringbuilder();
int index = text.indexof(replacestr);
if (index >= 0) {
string afterstr = null;
if (index > 0) {
string beforestr = text.substring(0, index);
afterstr = text.substring(index replacestr.length());
str.append(replaceall(beforestr, replacestr, newstr));
} else
afterstr = text.substring(replacestr.length());
str.append(newstr);
str.append(replaceall(afterstr, replacestr, newstr));
}
if (str.length() == 0)
return text;
return str.tostring();
}
/**
* 替换指定的字符串数组为一个字符串数组
* 速度比string.replaceall快3倍左右,比apache-common stringutils.replace快2倍左右
*
* @param text
* @param replacestrs
* @param newstrs
* @return
*/
public static string replaceallarray(string text, string[] replacestrs,
string[] newstrs) {
if (text.length() == 0)
return text;
stringbuilder str = new stringbuilder();
for (int i = 0; i < replacestrs.length; i ) {
string replacestr = replacestrs[i];
int index = text.indexof(replacestr);
if (index >= 0) {
string afterstr = null;
if (index > 0) {
string beforestr = text.substring(0, index);
afterstr = text.substring(index replacestr.length());
str
.append(replaceallarray(beforestr, replacestrs,
newstrs));
} else
afterstr = text.substring(replacestr.length());
str.append(newstrs[i]);
str.append(replaceallarray(afterstr, replacestrs, newstrs));
break;
}
}
if (str.length() == 0)
return text;
return str.tostring();
}
/**
* 解码html(将>,<,",&转换成>,<,",& )
*
* @param html
* @return
*/
public static string decodehtml(string html) {
if (isblank(html))
return "";
string[] replacestr = { "&", "<", ">", """ };
string[] newstr = { "&", "<", ">", "\"" };
return replaceallarray(html, replacestr, newstr);
}
/**
* 编码html(将>,<,",&
* 转换成>,<,",&)(高效率,来自freemarker模板源码,比replaceall速度快很多)
*
* @param html
* @return
*/
public static string encodehtml(string html) {
if (isblank(html))
return "";
int ln = html.length();
char c;
stringbuffer b;
for (int i = 0; i < ln; i ) {
c = html.charat(i);
if (c == '<' || c == '>' || c == '&' || c == '"') {
b = new stringbuffer(html.substring(0, i));
switch (c) {
case '<':
b.append("<");
break;
case '>':
b.append(">");
break;
case '&':
b.append("&");
break;
case '"':
b.append(""");
break;
}
i ;
int next = i;
while (i < ln) {
c = html.charat(i);
if (c == '<' || c == '>' || c == '&' || c == '"') {
b.append(html.substring(next, i));
switch (c) {
case '<':
b.append("<");
break;
case '>':
b.append(">");
break;
case '&':
b.append("&");
break;
case '"':
b.append(""");
break;
}
next = i 1;
}
i ;
}
if (next < ln)
b.append(html.substring(next));
html = b.tostring();
break;
}
}
return html;
}
/**
* md5加密
*
* @param plaintext
* 要加密的字符串
* @return 加密后的字符串
*/
public static string md5(string plaintext) {
stringbuffer buf = new stringbuffer("");
try {
messagedigest md = messagedigest.getinstance("md5");
md.update(plaintext.getbytes());
byte b[] = md.digest();
int i = 0;
for (int offset = 0; offset < b.length; offset ) {
i = b[offset];
if (i < 0)
i = 256;
if (i < 16)
buf.append("0");
buf.append(integer.tohexstring(i));
}
} catch (exception e) {
e.printstacktrace();
}
return buf.tostring();
}
/**
* md5加密(32)
*
* @param plaintext
* 要加密的字符串
* @return
*/
public final static string md5(string plaintext) {
char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
byte[] strtemp = plaintext.getbytes();
messagedigest mdtemp = messagedigest.getinstance("md5");
mdtemp.update(strtemp);
byte[] md = mdtemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i ) {
byte byte0 = md[i];
str[k ] = hexdigits[byte0 >>> 4 & 0xf];
str[k ] = hexdigits[byte0 & 0xf];
}
return new string(str);
} catch (exception e) {
}
return "";
}
}