ツールクラスStringUtil
35498 ワード
/**
* Copyright (c) 2008 CEPRI,Inc.All rights reserved.
* Created by 2008-4-25
*/
package com.cepri.cmm.utils;
/**
* @title :
* @description :
* @data:
*/
public class StringUtil {
/***************************************************************************
* java
**************************************************************************/
//
private static String[][] FilterChars={{"<","<"},{">",">"},{" "," "},{"\"","""},{"&","&"},
{"/","/"},{"\\","\"},{"
","<br>"}};
// javascript
private static String[][] FilterScriptChars={{"
","\'+\'\
\'+\'"},
{"\r"," "},{"\\","\'+\'\\\\\'+\'"},
{"\'","\'+\'\\\'\'+\'"}};
/**
* @description: ,1、direction r( ),l( )
* @param oldStr
* :
* @param strLen
* :
* @param padChar
* :
* @param direction
* :
* @return
*/
public static String padString(String oldStr, int strLen, char padChar,
char direction) {
String newStr = oldStr;
try {
if (oldStr.length() >= strLen) {
newStr = oldStr;
} else {
if (direction == 'r') {
while (newStr.length() < strLen) {
newStr = newStr + padChar;
}
} else {
while (newStr.length() < strLen) {
newStr = padChar + newStr;
}
}
}
return newStr;
} catch (Exception e) {
return oldStr;
}
}
/** Vector * */
public static Vector Str2Vect(String tStr, String sStr) {
Vector vector = new Vector();
StringTokenizer st = new StringTokenizer(tStr, sStr);
while (st.hasMoreTokens()) {
vector.add(st.nextToken());
}
return vector;
}
/** Vector , sStr * */
public static String Vect2Str(Vector tVect, String sStr) {
String reStr = "";
if (tVect.size() > 0)
reStr = (String) tVect.get(0);
for (int i = 1; i < tVect.size(); i++) {
reStr += sStr + (String) tVect.get(i);
}
return reStr;
}
/** Vector , * */
public static String Vect2Str(Vector tVect) {
String reStr = "";
for (int i = 0; i < tVect.size(); i++) {
reStr += (String) tVect.get(i);
}
return reStr;
}
/** , sStr * */
public static String[] Str2Strs(String tStr, String sStr) {
StringTokenizer st = new StringTokenizer(tStr, sStr);
String[] reStrs = new String[st.countTokens()];
int n = 0;
while (st.hasMoreTokens()) {
reStrs[n] = st.nextToken();
n++;
}
return reStrs;
}
/**
* separator str cnt
* @return String[]
* @author Administrator
* 2009-12-3
*/
public static String[] subStrToArray(String str,String separator,int cnt) {
String[] arr = StringUtil.Str2Strs(str, separator);
String[] ar = null;
if (arr.length > cnt) {
int num = (arr.length % cnt) > 0 ? 1 : 0;
ar = new String[arr.length / cnt + num];
int sta = 0;
int end = (arr[0].length() + 1) * cnt - 1;
for (int i = 0; i < ar.length; i++) {
ar[i] = str.substring(sta, end);
sta = end + 1;
end = sta +(arr[0].length() + 1) * cnt - 1;
if(sta> str.length()){
break;
}
if (end > str.length()) {
end = str.length();
ar[i+1] = str.substring(sta, end);
break;
}
}
}else{
ar =new String[1];
ar[0]=str;
}
return ar;
}
/** , sStr * */
public static String Strs2Str(String[] tStrs, String sStr) {
String reStr = "";
int len = tStrs.length;
if (len > 0) {
if (tStrs[0] != null)
reStr = tStrs[0];
}
for (int i = 1; i < len; i++) {
if (tStrs[i] != null) {
if (tStrs[i].length() > 0)
reStr += sStr + tStrs[i];
}
}
return reStr;
}
/** , sStr , '' * */
public static String Strs2Str(String[] tStrs, String sStr, String tostr) {
String reStr = "";
int len = tStrs.length;
if (len > 0) {
if (tStrs[0] != null)
reStr = "'" + tStrs[0] + "'";
}
for (int i = 1; i < len; i++) {
if (tStrs[i] != null) {
if (tStrs[i].length() > 0)
reStr += sStr + "'" + tStrs[i] + "'";
}
}
return reStr;
}
public static double numberDecimal(double d,int i){
BigDecimal b=new BigDecimal(d);
BigDecimal bd1=b.setScale(i,b.ROUND_HALF_UP);
d=bd1.doubleValue();
return d;
}
/** , * */
public static String Strs2Str(String[] tStrs) {
String reStr = "";
int len = tStrs.length;
for (int i = 0; i < len; i++) {
if (tStrs[i] != null) {
if (tStrs[i].length() > 0)
reStr += tStrs[i];
}
}
return reStr;
}
/** , Vector * */
public Vector Str2Vect(String tStr, int nleng) {
int strLength = tStr.length();
int ndiv = strLength / nleng;
Vector reVect = new Vector();
if (strLength % nleng == 0)
ndiv--;
for (int i = 0; i < (ndiv); i++) {
reVect.add(tStr.substring(i * nleng, (i + 1) * nleng));
}
reVect.add(tStr.substring(ndiv * nleng, strLength));
return reVect;
}
/** , , "-" * */
public static String Divide(String a, String b) {
try {
return String.valueOf(Double.valueOf(a).doubleValue()
/ Double.valueOf(b).doubleValue());
} catch (Exception e) {
return "-";
}
}
/** , re * */
public static String Divide(String a, String b, String re) {
try {
return String.valueOf(Double.valueOf(a).doubleValue()
/ Double.valueOf(b).doubleValue());
} catch (Exception e) {
return re;
}
}
/** , , re * */
public static String decrease(String a, String b, String re) {
try {
return String.valueOf(Double.valueOf(a).doubleValue()
- Double.valueOf(b).doubleValue());
} catch (Exception e) {
return re;
}
}
/** , , a * */
public static String decrease(String a, int b) {
try {
return String.valueOf(Integer.valueOf(a).intValue()
- Integer.valueOf(b).intValue());
} catch (Exception e) {
return a;
}
}
/** , , a * */
public static String decrease(String a, String b) {
try {
return String.valueOf(Double.valueOf(a).doubleValue()
- Double.valueOf(b).doubleValue());
} catch (Exception e) {
return a;
}
}
/** , a * */
public static String decrease(String a) {
try {
return String.valueOf(Double.valueOf(a).doubleValue() - 1);
} catch (Exception e) {
return a;
}
}
/** , re * */
public static String adding(String a, String b, String re) {
try {
return String.valueOf(Double.valueOf(a).doubleValue()
+ Double.valueOf(b).doubleValue());
} catch (Exception e) {
return re;
}
}
/** , a * */
public static String adding(String a, String b) {
try {
return String.valueOf(Double.valueOf(a).doubleValue()
+ Double.valueOf(b).doubleValue());
} catch (Exception e) {
return a;
}
}
/** , a * */
public static String adding(String a) {
try {
return String.valueOf(Double.valueOf(a).doubleValue() + 1);
} catch (Exception e) {
return a;
}
}
/** , re * */
public static String multiply(String a, String b, String re) {
try {
return String.valueOf(Double.valueOf(a).doubleValue()
* Double.valueOf(b).doubleValue());
} catch (Exception e) {
return re;
}
}
/** , a * */
public static String multiply(String a, String b) {
try {
return String.valueOf(Double.valueOf(a).doubleValue()
* Double.valueOf(b).doubleValue());
} catch (Exception e) {
return a;
}
}
/** (a-b)/b , re * */
public static String Tqb(String a, String b, String re) {
try {
return String.valueOf((Double.valueOf(a).doubleValue() - Double
.valueOf(b).doubleValue())
/ (Double.valueOf(b).doubleValue()));
} catch (Exception e) {
return re;
}
}
/** (a-b)/b , "-" * */
public static String Tqb(String a, String b) {
try {
return String.valueOf((Double.valueOf(a).doubleValue() - Double
.valueOf(b).doubleValue())
/ (Double.valueOf(b).doubleValue()));
} catch (Exception e) {
return "-";
}
}
/** String , str1 str2 * */
public static String replace(String str, String str1, String str2) {
int n = -1;
String subStr = "";
String re = "";
if ((n = str.indexOf(str1)) > -1) {
subStr = str.substring(n + str1.length(), str.length());
re = str.substring(0, n) + str2 + replace(subStr, str1, str2);
} else {
re = str;
}
return re;
}
/** Utf-8 * */
public static String toUtf8String(String s) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
byte[] b;
try {
b = Character.toString(c).getBytes("utf-8");
} catch (Exception ex) {
System.out.println(ex);
b = new byte[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0)
k += 256;
sb.append("%" + Integer.toHexString(k).toUpperCase());
}
}
}
return sb.toString();
}
/** GBK * */
public static String toGbkString(String s) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
byte[] b;
try {
b = Character.toString(c).getBytes("GBK");
} catch (Exception ex) {
System.out.println(ex);
b = new byte[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0)
k += 256;
sb.append("%" + Integer.toHexString(k).toUpperCase());
}
}
}
return sb.toString();
}
/**
* ,
*
* @param message
*
* @param separator
*
* @return
*/
public static String[] splitToArray(String message, String separator) {
List list = new ArrayList();
int start = 0;
int index = 0;
while ((index = message.indexOf(separator, start)) != -1) {
list.add(message.substring(start, index));
start = index + separator.length();
}
if (start < message.length()) {
list.add(message.substring(start, message.length()));
}
return (String[]) list.toArray(new String[list.size()]);
}
/** java.sql.date ,str formatStr * */
public static java.sql.Date str2SqlDate(String str, String formatStr) {
java.sql.Date sqlDate = new java.sql.Date(0);//
try {
sqlDate = new java.sql.Date(new java.text.SimpleDateFormat(
formatStr).parse(str).getTime());
} catch (ParseException e) {
e.printStackTrace();
}
return sqlDate;
}
/** */
public static String clear(Object obj) {
if (null == obj || "null".equals(obj))
return "";
return obj.toString();
}
/** , 0*/
public static String clearToZero(Object obj) {
if (null == obj)
return "0";
return obj.toString();
}
/** */
public static String clear(Object obj, String value) {
if (null == obj)
return value;
return obj.toString();
}
/** */
public static boolean isNull(Object obj) {
boolean flag = false;
if (null == obj || "".equals(obj))
flag = true;
return flag;
}
/** */
public static boolean isNotNull(Object obj) {
boolean flag = true;
if (null == obj || "".equals(obj))
flag = false;
return flag;
}
public static boolean isNotNull(List l) {
if (null != l && l.size() > 0)
return true;
return false;
}
public static boolean isNotNull(String str) {
if (null != str && str.trim().length() > 0)
return true;
return false;
}
public static boolean isNotNull(String[] str) {
if (null != str && str.length > 0)
return true;
return false;
}
public static String replaceStrNullOrNot(String str) {
if (null != str && str.length() > 0){
return str;
}
else{
return " ";
}
}
public static String replaceStrNullOrNot(Object obj) {
if (null != obj && !"".equals(obj)){
return obj.toString();
}
else{
return " ";
}
}
/**
*
* :isNull
* <p>
* :
* <p>
* :
*
* @param str
* :
* @return boolean
* <p>
* <p>
* @author HJun
* <p>
* @date Sep 2, 2009
* <p>
*/
public static boolean isNull(String str) {
if (null == str || "".equals(str.trim()))
return true;
return false;
}
/**
*
* :isNull
* <p>
* :
* <p>
* :
*
* @param list
* :
* @return boolean
* <p>
* <p>
* @author HJun
* <p>
* @date Sep 2, 2009
* <p>
*/
public static boolean isNull(List list) {
if (null == list || list.size() == 0)
return true;
return false;
}
/**
*
* :isNull
* <p>
* :
* <p>
* :
*
* @param str
* String[] :
* @return boolean
* <p>
* <p>
* @author HJun
* <p>
* @date Sep 2, 2009
* <p>
*/
public static boolean isNull(String[] str) {
if (null == str || str.length == 0)
return true;
return false;
}
public static String translateToChinese(String str) {
if(str!=null&&!"".equals(str)&&IsNumber(str)){
return translateToChinese(Integer.parseInt(str));
}else{
return "0";
}
}
/**
* @ translate
* @
* @param a
*
* @return
*/
public static String translateToChinese(int a) {
String[] units = { "", " ", " ", " ", " ", " ", " ", " ", " " };
String[] nums = { " ", " ", " ", " ", " ", " ", " ", " ", " ", " " };
String result = "";
if (a < 0) {
result = " ";
a = Math.abs(a);
}
String t = String.valueOf(a);
for (int i = t.length() - 1; i >= 0; i--) {
int r = (int) (a / Math.pow(10, i));
if (r % 10 != 0) {
String s = String.valueOf(r);
String l = s.substring(s.length() - 1, s.length());
result += nums[Integer.parseInt(l) - 1];
result += (units[i]);
} else {
if (!result.endsWith(" ")) {
result += " ";
}
}
}
String num = a + "";
/*
* 10-20 , 11 ,
*/
if (a == 10) {
return " ";
} else if (a > 10 && a < 20) {
return result.substring(1);
} else if (num.endsWith("0")) {
result = result.substring(0, result.length() - 1);
}
return result;
}
public static boolean eq(String str, Object o) {
if (null != o && isNotNull(o)) {
return o.equals(str);
}
return false;
}
public static boolean eq(Object o1, Object o2) {
if (null == o1 || isNull(o1)) {
if (o2 == null || isNull(o2)) {
return true;
} else {
return false;
}
} else {
return o1.equals(o2);
}
}
public static void main(String[] args) {
System.out.println(zero("222.02"));
System.out.println(IsFloat("1"));
System.out.println(mulite("1234.345","29.01234"));
}
/**
* @return String
* @author Administrator 2009-9-20
*/
public static String toString(List list) {
StringBuffer reStr = new StringBuffer("");
for (Object o : list) {
reStr.append(o.toString());
reStr.append(",");
}
return reStr.toString();
}
/**
*
*
* @param src
*
* @param num
*
* @return
*/
public static String cutString(String src, int num) {
if (isNull(src))
return src;
return src.substring(0, src.length() > num ? num : src.length());
}
public static double mulite(String str,String str2){
double d1=Double.parseDouble(str);
double d2=Double.parseDouble(str2);
return d1*d2;
}
/**
* @ :IsNumber
* @ :
* @param str:true ,false
* @return:
* @exception: null
*/
public static boolean IsNumber(String str){
Pattern pattern = Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();
}
/**
* @ :IsNumber
* @ :
* @param str:true ,false
* @return:
* @exception: null
*/
public static boolean IsFloat(String str){
Pattern pattern = Pattern.compile("\\d+[.]?\\d*");
return pattern.matcher(str).matches();
}
public static String getRequestStr(HttpServletRequest request,String param){
String result=request.getParameter(param);
if(StringUtil.isNull(result)){
result=(String)request.getAttribute(param);
}
if(StringUtil.isNull(result)){
result="";
}
result=result.trim();
return result;
}
/**
* XML < > ' " &
*
* @param str
*
* @return String
* @author zhangg
*/
public static String replace4XML(String str) {
if (str == null)
return "";
return str.replace("<", "<").replace(">", ">").replace("'", "'").replace("\"",
""").replace("&", "&");
}
/** “WebContent/skins/default/js/sotowerfunction.js” “tag2code()” ,
* @ :HtmlTag2String
* @ : html
* @param:String
* @return:String
*/
public static String HtmlTag2String(String temp){
temp = temp==null?"":temp;
return temp.replace("-lt;", "<").replace("-gt;", ">").replace("-amp;", "&");
}
/**
*
* :zero
* : , 0 0
* @param str
* @return
* @return String
* @author HJun
* @version 1.0
* Dec 17, 2009
*/
public static String zero(String str){
if(str.startsWith(".")){
str="0".concat(str);
}
return str;
}
/**
* @ :String2HtmlTag
* @ : “<”、“>” html
* @param:String
* @return:String
*/
public static String String2HtmlTag(String temp){
temp = temp==null?"":temp;
return temp.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """).replace("'", "´");
}
/**
* split("separator",'a') returns {"sep","r","tor"}
* @ :convertToUTF8
* @ :
* @param src
* @param char
* @return <br>
*/
public static String[] split(String src, char separator) {
if (src == null)
return null;
else
src = src.trim();
int sprtCount = count(src, separator);
if (sprtCount == 0) {
String[] det = new String[1];
det[0] = src;
return det;
}
String[] det = new String[sprtCount + 1];
int indexs = 0, indexe = 0;
for (int i = 0; i <= sprtCount; i++) {
indexe = src.indexOf(separator, indexs);
if (indexe == -1)
det[i] = src.substring(indexs);
else {
det[i] = src.substring(indexs, indexe);
indexs = indexe + 1;
}
}
return det;
}
/**
* @ :count
* @ :
* @param pStr
* String
* @return String
*/
public static int count(String ptr, char c) {
int coun = 0, pos = 0;
while ((pos = ptr.indexOf(c, pos)) != -1) {
coun++;
pos++;
}
return coun;
}
/**
* @ :count
* @ :
* @param pStr
* String
* @param c String
* @return String
*/
public static int count(String ptr, String c) {
int coun = 0, pos = 0;
while ((pos = ptr.indexOf(c, pos)) != -1) {
coun++;
pos += c.length();
}
return coun;
}
/**
* @ :getDoubleXDigit
* @ : X
* @param obj String
* @param x double
* @return double
*/
public static double getDoubleXDigit(String obj,double x) {
double tmpD = Double.parseDouble(obj);
double y = 10;
y = Math.pow(y, x);
tmpD = tmpD * y;
tmpD = Math.round(tmpD);
tmpD = tmpD / y;
return tmpD;
}
public static String getReplaceStr(String str,String regStr){
Pattern p = Pattern.compile(regStr);
Matcher m = p.matcher(str);
str = m.replaceAll("");
return str;
}
public static String getBackName (String fileName){
if(isNull(fileName)) return "";
if(fileName.lastIndexOf(".") < 0) return "";
return fileName.substring(fileName.lastIndexOf("."));
}
public static String getGBK(String str,String code){
try {
return new String(str.getBytes(),code);
} catch (UnsupportedEncodingException e) {
return null;
}
}
/**
* :getRequestStr
* :
* @param context
* @param string
* @return
* @return String
* @version 1.0
*/
public static String getRequestStr(WebContext context, String param) {
HttpServletRequest request=WebcUtils.getRequest(context);
return getRequestStr(request, param);
}
/** ArrayList * */
public static List<String> str2List(String tStr, String sStr) {
if(isNull(tStr)){
return null;
}
List<String> list = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(tStr, sStr);
while (st.hasMoreTokens()) {
list.add(st.nextToken());
}
return list;
}
/**
* :
* :
* @param context
* @version 1.0
*/
public static List<Map<String, String>> compareObj(Object obj1,Object obj2) throws Exception {
Class c = obj1.getClass();
Field fields[] = c.getDeclaredFields();
List<Map<String, String>> clist = new ArrayList<Map<String, String>>();
for (Field field :fields) {
field.setAccessible(true);
Object val1 = invokeMethod(obj1,field.getName(),null);
Object val2 = invokeMethod(obj2,field.getName(),null);
System.out.println(field.getName()+" : val1="+val1+"--- ----val2="+val2);
if(val1!=null&&val2!=null){
if(!val1.equals(val2)){
Map<String, String> ma = new HashMap<String, String>();
ma.put("beforValue", val1.toString());
ma.put("afterValue", val2.toString());
ma.put("colomnCode", convertString(field.getName()));
// ma.put("tableCode", c.getName());
clist.add(ma);
}
}
// else if(val1==null){
// if(val2!=null){
// // return true;
// }else{
//
// }
// }
//
}
return clist;
}
/**
* :
* :
* @param context
* @version 1.0
*/
public static Object invokeMethod(Object owner, String methodName, Object[] args) throws Exception {
Class ownerClass = owner.getClass();
System.out.println("Method="+methodName);
methodName = methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
Method method = null;
try {
method = ownerClass.getMethod("get" + methodName);
} catch (SecurityException e) {
} catch (NoSuchMethodException e) {
return " can't find 'get" + methodName + "' method";
}
return method.invoke(owner);
}
/**
* :
* :
* @param context
* @version 1.0
*/
public static String convertString(String s){
if(isNotNull(s)){
char[] c = s.toCharArray();
String str ="";
int i =0;
for(char ch : c){
if(Character.isUpperCase(ch)&&i>0){
str+="_";
}
str+=ch;
i++;
}
return str;
}else{
return "";
}
}
public static String convertString1(String s){
if(isNotNull(s)){
String ss = s.toLowerCase();
char[] carr = ss.toCharArray();
String str ="";
char temp = 0;
for(int i = 0; i < carr.length; i++){
if(i>0)temp = carr[i-1];
if(Character.isLetter(carr[i]) && temp == '_' ){
str += (carr[i]+"").toUpperCase();
}else{
str += carr[i];
}
}
str = str.replace("_", "");
return str;
}else{
return "";
}
}
/**
*
* @author zhangling
* SQL
*/
public static String ReplaceSqlLike(String strQuery)
{
String strRet = strQuery;
strRet = strRet.replace("/","//");
strRet = strRet.replace("'","''");
strRet = strRet.replace("%","/%");
strRet = strRet.replace("[","/[");
strRet = "'%" + strRet + "%' escape '/'";
return strRet;
}
/**
*
* @return 。 ,
*/
public static String getDirName(){
SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
Date date = new Date();
return df.format(date);
}
/**
*
* @param strings
* @param spilit_sign
* @return
*/
public static String stringConnect(String[] strings,String spilit_sign){
StringBuffer str=new StringBuffer();
for(int i=0;i<strings.length;i++){
str.append(strings[i]);
str.append(spilit_sign);
}
return str.toString();
}
/**
*
* @param str
* @return
*/
public static String stringFilter(String str){
String[] str_arr=stringSpilit(str,"");
for(int i=0;i<str_arr.length;i++){
for(int j=0;j<FilterChars.length;j++){
if(FilterChars[j][0].equals(str_arr[i]))
str_arr[i]=FilterChars[j][1];
}
}
return (stringConnect(str_arr,"")).trim();
}
/**
* ( (
) (\r))
* @param str
* @return
*/
public static String stringFilterScriptChar(String str){
String[] str_arr=stringSpilit(str,"");
for(int i=0;i<str_arr.length;i++){
for (int j = 0; j < FilterScriptChars.length; j++) {
if (FilterScriptChars[j][0].equals(str_arr[i]))
str_arr[i] = FilterScriptChars[j][1];
}
}
return(stringConnect(str_arr,"")).trim();
}
/**
*
* @param str
* @param spilit_sign
* @return
*/
public static String[] stringSpilit(String str,String spilit_sign){
String[] spilit_string=str.split(spilit_sign);
if(spilit_string[0].equals(""))
{
String[] new_string=new String[spilit_string.length-1];
for(int i=1;i<spilit_string.length;i++)
new_string[i-1]=spilit_string[i];
return new_string;
}
else
return spilit_string;
}
/**
*
* @param str
* @return
*/
public static String stringTransCharset(String str){
String new_str=null;
try{
new_str=new String(str.getBytes("iso-8859-1"),"GBK");
}
catch(Exception e){
e.printStackTrace();
}
return new_str;
}
/**
*
* @param args
*/
public static void main(String[] args){
//
String t_str1="<h1>StringDispose
\r\'\"</h1>";
System.out.println(" :"+t_str1);
System.out.println(" :"+StringUtils.stringFilter(t_str1));
//
String[] t_str_arr1={"PG_1","PG_2","PG_3"};
String t_str2=StringUtils.stringConnect(t_str_arr1,",");
System.out.println(t_str2);
//
String[] t_str_arr2=StringUtils.stringSpilit(t_str2,",");
for(int i=0;i<t_str_arr2.length;i++){
System.out.println(t_str_arr2[i]);
}
}
}