字符处理工具类

package j2ee.util;

import j2ee.tag.instance.TextBoxInt;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
@SuppressWarnings("unchecked")
public class StringUtil {
	public StringUtil() {
	}

	public static String trimToEmpty(String str) {
		return str == null ? "" : str.trim();
	}

	public static boolean isEmpty(String str) {
		return str == null || str.trim().length() == 0;
	}

	public static String notNull(String theString) {
		if (theString == null)
			return new String("");
		else
			return theString.trim();
	}

	public static String notNull(Object theString) {
		String str = (String) theString;
		return notNull(str);
	}

	public static String notNull(String name, Properties prop) {
		name = notNull(name);
		String str = notNull(prop.getProperty(name));
		return str;
	}

	public static String numberToLetter(int number, boolean upperCaseFlag)
			throws Exception {
		if (number < 1 || number > 26)
			throw new Exception(
					"The number is out of the proper range (1 to 26) to be converted to a letter.");
		int modnumber = number + 9;
		char thechar = Character.forDigit(modnumber, 36);
		if (upperCaseFlag)
			thechar = Character.toUpperCase(thechar);
		return (new StringBuilder()).append(thechar).toString();
	}

	
	public static Vector explode(String str, String tok) {
		StringTokenizer tokens = new StringTokenizer(str, tok);
		Vector v = new Vector();
		if (tokens.countTokens() > 1)
			while (tokens.hasMoreTokens()) {
				String s = tokens.nextToken().trim();
				if (!s.equals(""))
					v.add(s);
			}
		else
			v.add(str);
		return v;
	}

	public static String implode(String bind, Vector v) {
		String str = "";
		String oneStr = "";
		boolean needBind = false;
		for (Enumeration e = v.elements(); e.hasMoreElements();) {
			oneStr = (String) e.nextElement();
			str = (new StringBuilder(String.valueOf(str))).append(
					needBind ? bind : "").toString();
			str = (new StringBuilder(String.valueOf(str))).append(oneStr)
					.toString();
			needBind = true;
		}

		return str;
	}

	public static String implode(String bind, String str_array[]) {
		String str = "";
		String oneStr = "";
		boolean needBind = false;
		for (int i = 0; i < str_array.length; i++) {
			oneStr = str_array[i];
			str = (new StringBuilder(String.valueOf(str))).append(
					needBind ? bind : "").toString();
			str = (new StringBuilder(String.valueOf(str))).append(oneStr)
					.toString();
			needBind = true;
		}

		return str;
	}

	public static Vector toVector(String str_array[]) {
		Vector v = new Vector();
		for (int i = 0; i < str_array.length; i++)
			v.add(str_array[i]);

		return v;
	}

	public static String cutByMaxLength(String str, int max_num, String lan) {
		if (str.length() > max_num)
			try {
				str = str.substring(0, max_num);
				if (lan.equals("en")) {
					str = str.substring(0, str.lastIndexOf(" "));
					str = (new StringBuilder(String.valueOf(str))).append(
							" ...").toString();
				} else {
					int j;
					for (j = 0; j < max_num; j++) {
						byte word[] = str.substring(j, j + 1).getBytes();
						int tempInt = word[0] & 255;
						if (tempInt > 128)
							j++;
					}

					if (j != max_num)
						str = str.substring(0, max_num - 1);
					str = (new StringBuilder(String.valueOf(str)))
							.append("...").toString();
				}
			} catch (Exception e) {
				return str;
			}
		return str;
	}

	public static int getHzLen(String str) {
		int hzLen = 0;
		if (str != null && str.length() > 0)
			hzLen = str.getBytes().length;
		return hzLen;
	}

	public static String getFormStr(String name, Properties prop, String cmp,
			String selected_str) {
		return getFormStr(notNull(name, prop), cmp, selected_str);
	}

	public static String getFormStr(String value, String cmp,
			String selected_str) {
		if (value.equals(cmp))
			return selected_str;
		else
			return "";
	}

	public static Properties setEmptyValue(String name, Properties prop,
			String value) {
		if (notNull(name, prop).equals(""))
			prop.setProperty(name, notNull(value));
		return prop;
	}

	public static String codeConvert(String str) {
		if (str == null)
			return "";
		if (str.length() == 0)
			return "";
		else
			return str;
	}

	public static String codeEncode(String str) {
		if (str == null)
			return "";
		str = str.trim();
		if (str.length() == 0)
			return "";
		else
			return str;
	}

	public static String webCodeConvert(String str, String language) {
		if (str == null)
			return "";
		str = str.trim();
		if (str.length() == 0)
			return "";
		if (language == null)
			language = "";
		language = language.trim();
		if (language.toLowerCase().equals("cn"))
			language = "GBK";
		else if (language.toLowerCase().equals("jp"))
			language = "SJIS";
		else
			language = "";
		try {
			str = new String(str.getBytes(language), "8859_1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
	}

	public static String isoToGBConvert(String str) {
		if (str == null)
			return "";
		str = str.trim();
		if (str.length() == 0)
			return "";
		try {
			str = new String(str.getBytes("8859_1"), "gb2312");
		} catch (UnsupportedEncodingException unsupportedencodingexception) {
		}
		return str;
	}

	public static String notBlankNull(String theString) {
		if (theString == null)
			return "null";
		if (theString.trim().equals(""))
			return "''";
		else
			return (new StringBuilder("'")).append(theString.trim())
					.append("'").toString();
	}

	public static boolean hasCJK(String str) {
		boolean flag = false;
		if (str != null)
			flag = str.getBytes().length != str.length();
		return flag;
	}

	public static boolean isInteger(String str, int len) {
		if ("".equals(str))
			str = "0";
		if (len > 0 && str.length() != len)
			return false;
		try {
			Integer.parseInt(str);
		} catch (Exception exception) {
			return false;
		}
		return true;
	}

	public static boolean isEqual(char one[], char other[]) {
		boolean retVal = false;
		if (one != null && other != null && one.length == other.length) {
			for (int i = 0; i < one.length; i++) {
				if (one[i] != other[i])
					break;
				if (i == one.length - 1)
					retVal = true;
			}

		}
		return retVal;
	}

	public static boolean isDoubleValid(String str, int intLen) {
		if ("".equals(str))
			str = "0";
		Double.parseDouble(str);
		int pointPos = str.indexOf(".");
		if (pointPos == -1)
			return str.length() <= intLen;
		if (pointPos == 0)
			return true;
		return pointPos <= intLen;
	}

	public static int compareUtil(String s1, String s2) {
		int len = s1.length() - s2.length();
		if (len > 0) {
			for (int i = 0; i < len; i++)
				s2 = (new StringBuilder("0")).append(s2).toString();

		}
		if (len < 0) {
			len = -len;
			for (int i = 0; i < len; i++)
				s1 = (new StringBuilder("0")).append(s1).toString();

		}
		int result = s1.compareTo(s2);
		return result;
	}


	public static String collectionToDelimitedString(Collection c, String delim) {
		if (c == null)
			return "null";
		else
			return iteratorToDelimitedString(c.iterator(), delim);
	}

	public static String iteratorToDelimitedString(Iterator itr, String delim) {
		if (itr == null)
			return "null";
		StringBuffer sb = new StringBuffer();
		int i = 0;
		for (; itr.hasNext(); sb.append(itr.next()))
			if (i++ > 0)
				sb.append(delim);

		return sb.toString();
	}

	public static String arrayToDelimitedString(Object arr[], String delim) {
		return arrayToDelimitedString(arr, delim, "");
	}

	public static boolean isDigitOk(int num) {
		return num <= 0;
	}

	public static String arrayToDelimitedString(Object arr[], String delim,
			String quoteMark) {
		if (arr == null)
			return "null";
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < arr.length; i++) {
			if (i > 0)
				sb.append(delim);
			sb.append(quote(arr[i].toString(), quoteMark));
		}

		return sb.toString();
	}

	public static String quote(String str, String quoteMark) {
		return (new StringBuilder(String.valueOf(quoteMark))).append(str)
				.append(quoteMark).toString();
	}

	public static String[] commaDelimitedListToStringArray(String s) {
		return delimitedListToStringArray(s, ",");
	}

	public static String[] delimitedListToStringArray(String s, String delimiter) {
		if (s == null)
			return new String[0];
		if (delimiter == null)
			return (new String[] { s });
		List l = new LinkedList();
		int pos = 0;
		for (int delpos = 0; (delpos = s.indexOf(delimiter, pos)) != -1;) {
			l.add(s.substring(pos, delpos));
			pos = delpos + delimiter.length();
		}

		if (pos <= s.length())
			l.add(s.substring(pos));
		return (String[]) l.toArray(new String[l.size()]);
	}

	public static String getFileName(String path) {
		return getFileName(path, File.pathSeparator);
	}

	public static String getFileName(String path, String pathSeparator) {
		if (path == null)
			return null;
		int position = path.lastIndexOf(pathSeparator);
		if (position >= 0)
			return path.substring(position + 1);
		else
			return path;
	}

	public static String getMd5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			byte strTemp[] = s.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 & 15];
				str[k++] = hexDigits[byte0 & 15];
			}

			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}
	
	public static String toCommaSeparatorString(Object[] values){
		StringBuffer buffer = new StringBuffer();
		for(int i=0;i<values.length;i++){
			buffer.append(values[i])
				  .append(i==values.length-1?"":",");
		}
		return buffer.toString();
	}

}


package com.atom.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;

import BizServer.BizKernel.FilterCollection;

import com.atom.proxyModex.SupportAccess;
@SuppressWarnings("unchecked")
public class StringUtil {
	public StringUtil() {
	}

	public static String trimToEmpty(String str) {
		return str == null ? "" : str.trim();
	}
	
	//pxw
	public static boolean isTrimEmpty(String s){
		return s==null || s.trim().equals("");
	}
	
	//pxw
	public static String toSafeText(String s){
		return s==null?"":s;
	}
	
	//pxw
	public static boolean isEmpty(String str) {
		return str == null || str.length() == 0;
	}
	//pxw
	public static final String SplitString = "[]";
	public static String[] SplitTableAndText(String s){
			List<String> resultList = new ArrayList<String>();
			while(true){
				int begin = s.indexOf("[");
				int end = s.indexOf("]");
				if(begin<0 || end<0) break;
				String singleData = s.substring(begin+1, end);
				if(!StringUtil.isTrimEmpty(singleData))
					resultList.add(singleData);
				s=s.substring(end+1);
			}
			
			return resultList.toArray(new String[resultList.size()]);
	}

	public static String notNull(String theString) {
		if (theString == null)
			return new String("");
		else
			return theString.trim();
	}

	public static String notNull(Object theString) {
		String str = (String) theString;
		return notNull(str);
	}

	public static String notNull(String name, Properties prop) {
		name = notNull(name);
		String str = notNull(prop.getProperty(name));
		return str;
	}

	public static String numberToLetter(int number, boolean upperCaseFlag)
			throws Exception {
		if (number < 1 || number > 26)
			throw new Exception(
					"The number is out of the proper range (1 to 26) to be converted to a letter.");
		int modnumber = number + 9;
		char thechar = Character.forDigit(modnumber, 36);
		if (upperCaseFlag)
			thechar = Character.toUpperCase(thechar);
		return (new StringBuilder()).append(thechar).toString();
	}

	
	public static Vector explode(String str, String tok) {
		StringTokenizer tokens = new StringTokenizer(str, tok);
		Vector v = new Vector();
		if (tokens.countTokens() > 1)
			while (tokens.hasMoreTokens()) {
				String s = tokens.nextToken().trim();
				if (!s.equals(""))
					v.add(s);
			}
		else
			v.add(str);
		return v;
	}

	public static String implode(String bind, Vector v) {
		String str = "";
		String oneStr = "";
		boolean needBind = false;
		for (Enumeration e = v.elements(); e.hasMoreElements();) {
			oneStr = (String) e.nextElement();
			str = (new StringBuilder(String.valueOf(str))).append(
					needBind ? bind : "").toString();
			str = (new StringBuilder(String.valueOf(str))).append(oneStr)
					.toString();
			needBind = true;
		}

		return str;
	}

	public static String implode(String bind, String str_array[]) {
		String str = "";
		String oneStr = "";
		boolean needBind = false;
		for (int i = 0; i < str_array.length; i++) {
			oneStr = str_array[i];
			str = (new StringBuilder(String.valueOf(str))).append(
					needBind ? bind : "").toString();
			str = (new StringBuilder(String.valueOf(str))).append(oneStr)
					.toString();
			needBind = true;
		}

		return str;
	}

	public static Vector toVector(String str_array[]) {
		Vector v = new Vector();
		for (int i = 0; i < str_array.length; i++)
			v.add(str_array[i]);

		return v;
	}

	public static String cutByMaxLength(String str, int max_num, String lan) {
		if (str.length() > max_num)
			try {
				str = str.substring(0, max_num);
				if (lan.equals("en")) {
					str = str.substring(0, str.lastIndexOf(" "));
					str = (new StringBuilder(String.valueOf(str))).append(
							" ...").toString();
				} else {
					int j;
					for (j = 0; j < max_num; j++) {
						byte word[] = str.substring(j, j + 1).getBytes();
						int tempInt = word[0] & 255;
						if (tempInt > 128)
							j++;
					}

					if (j != max_num)
						str = str.substring(0, max_num - 1);
					str = (new StringBuilder(String.valueOf(str)))
							.append("...").toString();
				}
			} catch (Exception e) {
				return str;
			}
		return str;
	}

	public static int getHzLen(String str) {
		int hzLen = 0;
		if (str != null && str.length() > 0)
			hzLen = str.getBytes().length;
		return hzLen;
	}

	public static String getFormStr(String name, Properties prop, String cmp,
			String selected_str) {
		return getFormStr(notNull(name, prop), cmp, selected_str);
	}

	public static String getFormStr(String value, String cmp,
			String selected_str) {
		if (value.equals(cmp))
			return selected_str;
		else
			return "";
	}

	public static Properties setEmptyValue(String name, Properties prop,
			String value) {
		if (notNull(name, prop).equals(""))
			prop.setProperty(name, notNull(value));
		return prop;
	}

	public static String codeConvert(String str) {
		if (str == null)
			return "";
		if (str.length() == 0)
			return "";
		else
			return str;
	}

	public static String codeEncode(String str) {
		if (str == null)
			return "";
		str = str.trim();
		if (str.length() == 0)
			return "";
		else
			return str;
	}

	public static String webCodeConvert(String str, String language) {
		if (str == null)
			return "";
		str = str.trim();
		if (str.length() == 0)
			return "";
		if (language == null)
			language = "";
		language = language.trim();
		if (language.toLowerCase().equals("cn"))
			language = "GBK";
		else if (language.toLowerCase().equals("jp"))
			language = "SJIS";
		else
			language = "";
		try {
			str = new String(str.getBytes(language), "8859_1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
	}

	public static String isoToGBConvert(String str) {
		if (str == null)
			return "";
		str = str.trim();
		if (str.length() == 0)
			return "";
		try {
			str = new String(str.getBytes("8859_1"), "gb2312");
		} catch (UnsupportedEncodingException unsupportedencodingexception) {
		}
		return str;
	}

	public static String notBlankNull(String theString) {
		if (theString == null)
			return "null";
		if (theString.trim().equals(""))
			return "''";
		else
			return (new StringBuilder("'")).append(theString.trim())
					.append("'").toString();
	}

	public static boolean hasCJK(String str) {
		boolean flag = false;
		if (str != null)
			flag = str.getBytes().length != str.length();
		return flag;
	}

	public static boolean isInteger(String str, int len) {
		if ("".equals(str))
			str = "0";
		if (len > 0 && str.length() != len)
			return false;
		try {
			Integer.parseInt(str);
		} catch (Exception exception) {
			return false;
		}
		return true;
	}

	public static boolean isEqual(char one[], char other[]) {
		boolean retVal = false;
		if (one != null && other != null && one.length == other.length) {
			for (int i = 0; i < one.length; i++) {
				if (one[i] != other[i])
					break;
				if (i == one.length - 1)
					retVal = true;
			}

		}
		return retVal;
	}

	public static boolean isDoubleValid(String str, int intLen) {
		if ("".equals(str))
			str = "0";
		Double.parseDouble(str);
		int pointPos = str.indexOf(".");
		if (pointPos == -1)
			return str.length() <= intLen;
		if (pointPos == 0)
			return true;
		return pointPos <= intLen;
	}

	public static int compareUtil(String s1, String s2) {
		int len = s1.length() - s2.length();
		if (len > 0) {
			for (int i = 0; i < len; i++)
				s2 = (new StringBuilder("0")).append(s2).toString();

		}
		if (len < 0) {
			len = -len;
			for (int i = 0; i < len; i++)
				s1 = (new StringBuilder("0")).append(s1).toString();

		}
		int result = s1.compareTo(s2);
		return result;
	}


	public static String collectionToDelimitedString(Collection c, String delim) {
		if (c == null)
			return "null";
		else
			return iteratorToDelimitedString(c.iterator(), delim);
	}

	public static String iteratorToDelimitedString(Iterator itr, String delim) {
		if (itr == null)
			return "null";
		StringBuffer sb = new StringBuffer();
		int i = 0;
		for (; itr.hasNext(); sb.append(itr.next()))
			if (i++ > 0)
				sb.append(delim);

		return sb.toString();
	}

	public static String arrayToDelimitedString(Object arr[], String delim) {
		return arrayToDelimitedString(arr, delim, "");
	}

	public static boolean isDigitOk(int num) {
		return num <= 0;
	}

	public static String arrayToDelimitedString(Object arr[], String delim,
			String quoteMark) {
		if (arr == null)
			return "null";
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < arr.length; i++) {
			if (i > 0)
				sb.append(delim);
			sb.append(quote(arr[i].toString(), quoteMark));
		}

		return sb.toString();
	}

	public static String quote(String str, String quoteMark) {
		return (new StringBuilder(String.valueOf(quoteMark))).append(str)
				.append(quoteMark).toString();
	}

	public static String[] commaDelimitedListToStringArray(String s) {
		return delimitedListToStringArray(s, ",");
	}

	public static String[] delimitedListToStringArray(String s, String delimiter) {
		if (s == null)
			return new String[0];
		if (delimiter == null)
			return (new String[] { s });
		List l = new LinkedList();
		int pos = 0;
		for (int delpos = 0; (delpos = s.indexOf(delimiter, pos)) != -1;) {
			l.add(s.substring(pos, delpos));
			pos = delpos + delimiter.length();
		}

		if (pos <= s.length())
			l.add(s.substring(pos));
		return (String[]) l.toArray(new String[l.size()]);
	}

	public static String getFileName(String path) {
		return getFileName(path, File.pathSeparator);
	}

	public static String getFileName(String path, String pathSeparator) {
		if (path == null)
			return null;
		int position = path.lastIndexOf(pathSeparator);
		if (position >= 0)
			return path.substring(position + 1);
		else
			return path;
	}

	public static String getMd5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			byte strTemp[] = s.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 & 15];
				str[k++] = hexDigits[byte0 & 15];
			}

			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}
	
	//pxw
	public static String Format(String patternStr,String... s){
		for(int i=0;i<s.length;i++){
			patternStr = patternStr.replace("{"+i+"}", s[i]);
		}
		return patternStr;
	}
	
	public static int[] toIntegerArray(String[] s){
		int[] toInt=new int[s.length];
		for(int i=0;i<s.length;i++){
			toInt[i]=Integer.valueOf(s[i]);
		}
		return toInt;
	}	
	
	public static String trimForChar(String s,char split){
		s = trimToEmpty(s);
		if(isEmpty(s)) return s;
		char[] chars = s.toCharArray();
		int begin = 0;
		int end = 0;
		boolean content = false;
		for(int i=0;i<chars.length;i++){
			if(chars[i]==split){
				if(!content){
					begin = i+1;
				}
			}else{
				content = true;
				end = i+1;
			}
		}
		if(end==0){
			return "";
		}
		s = s.substring(begin,end);
		return s;
	}
	
	public static void main(String[] args) throws Exception {
//		String ids = ",,,,";
//		System.out.println(trimForChar(ids, ','));
//		String rep = "aaa{1}bbb{0}";
//		System.out.println(Format(rep, "bb","aa"));
		String ids = "aaa,aaa,,,";
		System.out.println(ids.split(",").length);
	}

	public static int[] toIntegerArray(String ids) { 
		if(ids==null){
			return null;
		}
		if(ids.endsWith(",")){
			ids=ids.substring(0, ids.length()-1);
		}
		String[] id=ids.split(",");
		return toIntegerArray(id);
	}	
	
	public static String trimFirstAndLast (String s,String split) {
		s = trimToEmpty(s);
		if(isEmpty(s)) return s;
		if(s.endsWith(split)){
			s=s.substring(0, s.length()-1);
		}
		if(s.substring(0, 1).equalsIgnoreCase(split)){
		s=s.substring(1);
		}
		return s;
	}	
	
	/**
	 * String转Date
	 * @param date 日期时间
	 * @param dateFormat 日期格式
	 * @return date
	 * @author sean
	 */
	public static Date str2date(String date,String dateFormat){
		try {
			DateFormat format = new SimpleDateFormat(dateFormat);//yyyy-MM-dd HH:mm:ss
		    Date redate = format.parse(date);  // Thu Jan 18 00:00:00 CST 2007
		    return redate;
		} catch (Exception e) {    
		    e.printStackTrace();    
		}  
		return null;
	}
	
	/**
	 * string转list
	 * @param str
	 * @return list
	 */
	public static List str2list(String str){
		if(str==null || str==""){
			return null;
		}
		if(str.endsWith(",")){
			str=str.substring(0, str.length()-1);
		}
		ArrayList list = new ArrayList();
		String[] id=str.split(",");
		for(int i=0;i<id.length;i++){
			list.add(id[i]);
		}
		return list;
	}
}
posted @ 2011-07-20 16:29  上善¤若水  阅读(104)  评论(0编辑  收藏  举报