工具类---字符串操作 StrUtil

package com.luang.util.common;


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import com.luang.util.date.DateUtil;


public class StrUtil
{
public static final String STRING_SPILTOR = ";";
public static final String JSON_STRING_SPILTOR = ",";


public static String getLastToken(String str, String tokenSeparator)
{
return str.substring(str.lastIndexOf(tokenSeparator) + 1, str.length());
}


public static boolean isNull(String s)
{
return (s == null) || (s.length() < 1);
}


public static boolean isNull(String s, String val)
{
return (isNull(s)) || (s.compareTo(val) == 0);
}


public static String stackTrace(Throwable t)
{
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
String s = sw.toString();
try {
sw.close();
} catch (IOException localIOException) {
}
return s;
}


public static String dbString(String v) {
StringBuffer sb = new StringBuffer();
return "'" + v + "'";
}


public static String dumpHashTable(Hashtable table, boolean html) {
Enumeration keys = table.keys();
Enumeration values = table.elements();
StringBuffer sb = new StringBuffer();
String eof = "\n";
if (html)
eof = "<br>\n";
while (keys.hasMoreElements()) {
sb.append(" key [").append(keys.nextElement().toString()).append("] = [").append(
values.nextElement().toString()).append("]").append(eof);
}
return sb.toString();
}


public static String addURLParameter(String URL, String paramName, String paramValue)
{
String param = paramName + "=" + paramValue;
return addURLParameter(URL, param);
}


public static String addURLParameter(String URL, String parameter)
{
StringBuffer sb = new StringBuffer(URL);
if (URL.lastIndexOf('?') == -1)
sb.append("?");
else
sb.append("&");
sb.append(parameter);
return sb.toString();
}


public static String remove(String str, String until)
{
String val = null;
int indx = str.indexOf(until);
if (indx != -1)
val = str.substring(indx + until.length(), str.length());
return val;
}


public static Long String2Long(String str)
{
Long l = new Long(0L);
try {
l = Long.valueOf(str);
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
return l;
}


public static int String2PageId(String str)
{
int i;
try
{
i = Integer.parseInt(str);
}
catch (NumberFormatException ex)
{
i = 1;
}
return i;
}


public static String NullToString(String str)
{
if (str == null)
str = "";
return str;
}


public static String NullToZero(String str)
{
if (str == null)
str = "0";
return str;
}


public static BigDecimal NullToBigDecimal(BigDecimal decimal)
{
if (decimal == null)
decimal = BigDecimal.valueOf(0L);
return decimal;
}


public static String htmlToSql(String strHtml)
{
StringBuffer strSql = null;
if (strHtml != null) {
strSql = new StringBuffer();
for (int i = 0; i < strHtml.length(); i++) {
String temp = strHtml.substring(i, i + 1);
if (temp.equals("'"))
strSql.append("''");
else {
strSql.append(temp);
}
}
return strSql.toString();
}
return "";
}


public static String sqlToHtml(String strSql)
{
StringBuffer strHtml = null;
if (strSql != null) {
strHtml = new StringBuffer();
for (int i = 0; i < strSql.length(); i++) {
String temp = strSql.substring(i, i + 1);
if (temp.equals("'"))
strHtml.append("'");
else if (temp.equals(">"))
strHtml.append("&gt;");
else if (temp.equals("<"))
strHtml.append("&lt;");
else if (temp.equals("&"))
strHtml.append("&amp;");
else if (temp.equals("\""))
strHtml.append("&quot;");
else {
strHtml.append(temp);
}
}
return strHtml.toString();
}
return "";
}


public static String formatDouble(double dblDigit, int scale)
{
String temp = "##,###,###,###,###.";
for (int i = 0; i < scale; i++) {
temp = temp + "#";
}
return new DecimalFormat(temp).format(dblDigit);
}


public static String urlEncode(String strURL)
{
try
{
strURL = URLEncoder.encode(strURL, "gb2312");
} catch (UnsupportedEncodingException localUnsupportedEncodingException) {
}
return strURL;
}


public static String urlDecode(String strURL)
{
try
{
strURL = URLDecoder.decode(strURL, "gb2312");
} catch (UnsupportedEncodingException localUnsupportedEncodingException) {
}
return strURL;
}


public static HashMap getFilesOfJPG(String filePath)
throws Exception
{
HashMap hmFile = new HashMap();
int index = 0;
File file = new File(filePath);
String[] files = file.list();
if (files != null) {
for (int i = 0; i < files.length; i++) {
String fileName = files[i];
index = fileName.indexOf(".");
if (index >= 0) {
String key = fileName.substring(0, index);
key = key.toLowerCase();
String extend = fileName.substring(index + 1,
fileName.length());
extend = extend.toLowerCase();
hmFile.put(key, fileName);
}
}
}


return hmFile;
}


public static int getDigitCountForString(String str)
throws Exception
{
String temp = "";
int count = 0;
for (int i = 0; i < str.length(); i++) {
temp = str.substring(i, i + 1);
if ((temp.compareTo("0") >= 0) && (temp.compareTo("9") <= 0)) {
count++;
}
}
return count;
}


public static int getTerm(Date rxDate, Date curDate) throws Exception {
int termNo = 0;
String strRXDate = DateUtil.formatDate(rxDate, 0);
String strCurDate = DateUtil.formatDate(curDate, 0);
if (strRXDate.equals(""))
return termNo;
if (strCurDate.equals(""))
return termNo;
int rxYear = Integer.parseInt(strRXDate.substring(0, 4));
int rxMonth = Integer.parseInt(strRXDate.substring(5, 7));
int curYear = Integer.parseInt(strCurDate.substring(0, 4));
int curMonth = Integer.parseInt(strCurDate.substring(5, 7));
if (rxYear < curYear) {
int count = 0;
int month = curMonth - rxMonth;
if (rxMonth > 7) {
if (month < 0)
count = 0;
else
count = 1;
} else if (month > 5)
count = 2;
else
count = 1;
termNo = (curYear - rxYear) * 2 + count;
} else if (rxYear == curYear) {
int month = curMonth - rxMonth;
if (month > 5)
termNo = 2;
else
termNo = 1;
}
return termNo;
}


public static String[] splitString(String str, String splitor, int count)
throws Exception
{
String[] strResult = new String[count];
int i = 0;
int index = 0;
for (index = str.indexOf(splitor); index >= 0; ) {
String temp = str.substring(0, index);
strResult[i] = temp;
str = str.substring(index + 1, str.length());
index = str.indexOf(splitor);
i++;
}


strResult[i] = str;
return strResult;
}


public static Vector splitString(String str, String splitor)
throws Exception
{
Vector vResult = new Vector();
int i = 0;
int index = 0;
for (index = str.indexOf(splitor); index >= 0; ) {
String temp = str.substring(0, index);
vResult.add(temp);
str = str.substring(index + 1, str.length());
index = str.indexOf(splitor);
i++;
}


vResult.add(str);
return vResult;
}


public static double getRate(double numerator, double denominator, int decimalLength)
{
int[] length = { 100, 1000, 10000, 100000, 1000000, 10000000 };
double rate = 0.0D;
rate = numerator / denominator;
rate *= length[decimalLength];
rate = Math.round(rate);
rate = rate * 100.0D / length[decimalLength];
return rate;
}


public static String digitToUpper(String strDigit)
{
String result = "";
String[] digits = { "锛?", "涓?", "浜?", "涓?", "鍥?",
"浜?", "鍏?", "涓?", "鍏?", "涔?" };
int length = strDigit.length();
String strChar = "";
int digit = 0;
String max = "9";
String min = "0";
for (int i = 0; i < length; i++) {
strChar = strDigit.substring(i, i + 1);
if ((strChar.compareTo(min) >= 0) && (strChar.compareTo(max) <= 0)) {
digit = Integer.parseInt(strChar);
strChar = digits[digit];
}
result = result + strChar;
}


return result;
}


public static String intToUpper(String strInt)
{
String result = "";
String[] digits = { "锛?", "涓?", "浜?", "涓?", "鍥?",
"浜?", "鍏?", "涓?", "鍏?", "涔?" };
String[] units = { "", "鍗?", "鐧?", "鍗?", "涓?",
"鍗?", "鐧?", "鍗?", "浜?", "鍗?", "鐧?",
"鍗?", "涓?", "鍗?", "鐧?", "鍗?" };
int length = 0;
int bit = 0;
String strChar = "";
String strCharUpper = "";
int digit = 0;
String max = "9";
String min = "0";
int nInt = 0;
String flag = "0";
try {
nInt = Integer.parseInt(strInt);
strInt = String.valueOf(nInt);
} catch (Exception e) {
return strInt;
}
length = strInt.length();
bit = length;
for (int i = 0; i < length; i++) {
strChar = strInt.substring(i, i + 1);
if ((strChar.compareTo(min) >= 0) && (strChar.compareTo(max) <= 0)) {
digit = Integer.parseInt(strChar);
strCharUpper = digits[digit];
}
if ((nInt >= 10) && (nInt < 20) && (i == 0))
flag = "1";
else if ((nInt <= 9) || (nInt >= 100) || (strChar.compareTo(min) != 0))
result = result + strCharUpper;
bit--;
result = result + units[bit];
}


return result;
}


public static String getErrorMsg(Exception e)
{
System.out.println(" ################### ");
System.out.println(" @error: " + e.toString());
System.out.println(" ################### ");
String error = e.getMessage();
if (error == null)
error = "";
if (error.indexOf("error.") < 0)
error = "error.system";
return error;
}


public static float getRoundFloat(float f, int type)
throws Exception
{
BigDecimal b = new BigDecimal(f);
float f1 = b.setScale(type, 4).floatValue();
return f1;
}


public static String getLimitLengthString(String str, int len, String symbol)
throws UnsupportedEncodingException
{
if ((str == null) || (str.equals("")))
return str;
if (len == 0)
return str;
int counterOfDoubleByte = 0;
byte[] b = str.getBytes("GBK");
if (b.length <= len)
return str;
for (int i = 0; i < len; i++) {
if (b[i] < 0)
counterOfDoubleByte++;
}
if (counterOfDoubleByte % 2 == 0) {
return new String(b, 0, len, "GBK") + symbol;
}
return new String(b, 0, len - 1, "GBK") + symbol;
}


public static String getPropertyValueOfObject(Object obj)
{
String result = "";
Class cObj = obj.getClass();
Field[] fields = cObj.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field fieldObj = fields[i];
if ((fieldObj.getName().equals("logUtil")) ||
(fieldObj.getName().equals("ds")) ||
(fieldObj.getName().equals("alArea")) ||
(fieldObj.getName().equals("serialVersionUID")) ||
(fieldObj.getName().equals("alOrder")) ||
(fieldObj.getName().equals("sql"))) continue;
String temp = fieldObj.getName();
String firstWord = temp.substring(0, 1);
temp = firstWord.toUpperCase() +
temp.substring(1, temp.length());
String methodName = "get" + temp;
try {
Method methodObj = cObj.getMethod(methodName, null);
String methodValue = "";
Object valueObj = methodObj.invoke(obj, null);
if (valueObj != null)
methodValue = NullToString(valueObj.toString());
result = result + fieldObj.getName() + ":" + methodValue +
";";
} catch (Exception e) {
e.printStackTrace();
}


}


return result;
}




public static String interception(double v1) {
String apjs = String.valueOf(v1);
int m = apjs.indexOf(".");
if (apjs.length() > m + 2)
apjs = apjs.substring(0, m + 3);
return apjs;
}


public static String formatString(String strSrc, String[] objs)
{
StringBuffer sbTemp = new StringBuffer();
int i = 0;
String temp = "";
int index = 0;
for (index = strSrc.indexOf("%"); (index > -1) && (objs.length > i); i++) {
sbTemp.append(strSrc.substring(0, index));
temp = objs[i];
sbTemp.append(temp);
strSrc = strSrc.substring(index + 2, strSrc.length());
index = strSrc.indexOf("%");
}


sbTemp.append(strSrc);
return sbTemp.toString();
}


public static String matcherStr(String str, String cp, String replacement)
{
if ((str == null) || (str.equals(""))) {
return "";
}
String txt = str;
Pattern p = Pattern.compile(cp, 2);
Matcher m = p.matcher(txt);
txt = m.replaceAll(replacement);
return txt;
}


public static String getClass1By(String class2)
{
if ((class2 == null) || (class2.equals("")))
return "";
String class1 = "";
if (class2.length() > 4)
class1 = class2.substring(0, 4);
return class1;
}


public static String formatString(String srcStr, char fillChar, int len, int direct)
{
String retStr = srcStr;
if (srcStr != null) {
if (srcStr.length() > len) {
retStr = retStr.substring(0, len);
} else if (srcStr.length() < len) {
StringBuffer sf = new StringBuffer();
for (int i = 0; i < len - srcStr.length(); i++) {
sf.append(fillChar);
}
if (direct == 0)
retStr = sf.toString() + retStr;
else
retStr = retStr + sf.toString();
}
} else {
StringBuffer sf = new StringBuffer();
for (int i = 0; i < len; i++) {
sf.append(fillChar);
}
retStr = sf.toString();
}
return retStr;
}


public static String formatDouble(double dblDigit)
{
String pattern = "###################.###";
DecimalFormat format = new DecimalFormat(pattern);
String result = format.format(dblDigit);
return result;
}


public static String replace(String targetStr, String beReplace, String replace)
{
if (targetStr == null)
return null;
if ((beReplace == null) || (beReplace.equals("")))
return targetStr;
if (replace == null)
replace = "";
StringBuffer stringbuffer = new StringBuffer();
int i = 0;
int index = targetStr.indexOf(beReplace);
int length = beReplace.length();
for (; index > -1; index = targetStr.indexOf(beReplace, i)) {
stringbuffer.append(targetStr.substring(i, index) + replace);
i = index + length;
}


stringbuffer.append(targetStr.substring(i));
return stringbuffer.toString();
}


public static String escapeChar(String str)
{
String retvalue = "";
retvalue = replace(str, "&", "&amp;");
return retvalue;
}


public static String reEscapeChar(String str)
{
String retvalue = "";
retvalue = replace(str, "&amp;", "&");
return retvalue;
}


public static String replaceFirst(String targetStr, String beReplace, String replace)
{
if (targetStr == null)
return null;
if ((beReplace == null) || (beReplace.equals("")))
return targetStr;
if (replace == null)
replace = "";
StringBuffer stringbuffer = new StringBuffer();
int i = 0;
int length = beReplace.length();
int index = targetStr.indexOf(beReplace);
if (index > -1) {
stringbuffer.append(targetStr.substring(i, index) + replace);
i = index + length;
stringbuffer.append(targetStr.substring(i));
return stringbuffer.toString();
}
return targetStr;
}


public static String replaceLast(String targetStr, String beReplace, String replace)
{
if (targetStr == null)
return null;
if ((beReplace == null) || (beReplace.equals("")))
return targetStr;
if (replace == null)
replace = "";
StringBuffer str = new StringBuffer(512);
for (int i = targetStr.length(); i > 0; i--) {
str.append(targetStr.charAt(i - 1));
}
String temp = replaceFirst(str.toString(), beReplace, replace);
str = new StringBuffer(512);
for (int i = temp.length(); i > 0; i--) {
str.append(temp.charAt(i - 1));
}
return str.toString();
}


public static String utf8Togb2312(String str)
{
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case '+':
sb.append(' ');
break;
case '%':
try {
sb.append((char)Integer.parseInt(
str.substring(i + 1, i + 3), 16));
}
catch (NumberFormatException e) {
throw new IllegalArgumentException();
}
i += 2;
break;
default:
sb.append(c);
}
}


String result = sb.toString();
String res = null;
try {
byte[] inputBytes = result.getBytes("8859_1");
res = new String(inputBytes, "UTF-8");
} catch (Exception localException) {
}
return res;
}


public static String charsetDeCode(String str)
{
if ("".equals(str)) {
return "";
}


StringBuffer sb = new StringBuffer("");
str = str.replace(" ", "");
try {
for (int i = 0; i < str.length() - 3; i += 4)
sb.append((char)Integer.valueOf(str.substring(i, i + 4), 16).intValue());
}
catch (Exception e) {
System.out.print(e.getStackTrace());
e.getStackTrace();
}


return sb.toString();
}


public static String charsetEncode(String str)
{
if ("".equals(str)) {
return "";
}


StringBuffer strBuff = new StringBuffer("");
try {
byte[] b = str.getBytes("UTF-16");
for (int n = 0; n < b.length; n++) {
str = Integer.toHexString(b[n] & 0xFF);
if (str.length() == 1)
strBuff.append("0").append(str);
else {
strBuff.append(str);
}


}


str = strBuff.toString().toUpperCase().substring(4);


char[] chs = str.toCharArray();
strBuff.delete(0, strBuff.length());
for (int i = 0; i < chs.length; i += 4)
strBuff.append(chs[i])
.append(chs[(i + 1)])
.append(chs[(i + 2)])
.append(chs[(i + 3)])
.append(" ");
}
catch (Exception e) {
System.out.print(e.getStackTrace());
e.getStackTrace();
}


return strBuff.toString();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值