`
guoxuepeng
  • 浏览: 38605 次
文章分类
社区版块
存档分类
最新评论

工具类---字符串操作 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();
}
}
分享到:
评论

相关推荐

    字符串过滤类(StrUtil)

    在Java编程语言中,`StrUtil`类通常指的是一个实用工具类,用于处理和操作字符串。这个类可能包含了各种方便的方法,比如字符串的拼接、分割、格式化、检查是否为空等。`StrUtil`不是Java标准库的一部分,但它是许多...

    将对象转换为json串的工具类.docx

    `Obj2StrUtil` 是一个Java工具类,主要用于将Java对象转换成JSON格式的字符串。在Java中,对象到JSON的转换是常见的操作,尤其是在处理Web服务或者数据序列化时。这个工具类提供了一个方便的方法 `obj2Str`,该方法...

    基于Java的源码-Hutool (Java基础工具类).zip

    例如,使用Hutool的DateUtil进行日期格式化,StrUtil进行字符串处理,FileUtil进行文件操作,HttpUtil进行网络请求等。 6. **源码阅读指南** 开始阅读Hutool源码前,建议先熟悉其模块划分,然后选择感兴趣的或者...

    将对象转换为json串的工具类.pdf

    `Obj2StrUtil` 是一个Java工具类,它的主要功能是将Java对象转换成JSON格式的字符串。这个类主要处理了四种类型的对象:Map、List、数组以及普通的Java Bean对象。以下是这个类的具体解析: 1. **处理Map对象** `...

    JAVA工具类项目(用于平时的开发)

    Hutool是这个压缩包中提到的一个知名Java工具库,它集成了大量的实用工具类,涵盖了字符串处理、日期时间操作、文件I/O、网络通信等多个领域。 Hutool的详细知识点包括: 1. **字符串工具**:Hutool提供了丰富的...

    hutool工具类,集成了大部分util工具,减少开发代码.rar

    2. **字符串操作**:StrUtil是Hutool中的字符串工具类,包含了大量的静态方法,如字符串格式化、拼接、替换、截取等,使得字符串处理变得更加高效。 3. **文件操作**:FileUtil提供了丰富的文件操作功能,如读写...

    java程序中处理一个包含诡异的不可见的字符。

    处理这类问题需要深入理解字符编码和字符串处理的原理。 首先,我们要了解字符编码。在Java中,标准的字符编码是Unicode,它包含了世界上几乎所有的字符。Unicode编码使用整数来表示每一个字符,这个整数称为码点。...

    Hutool常用方法api

    StrUtil是Hutool中处理字符串的工具类,它提供了检查字符串是否为空、填充字符串、格式化字符串以及正则表达式匹配等功能: ```java boolean isEmpty = StrUtil.isEmpty(str); // 判断字符串是否为空 boolean ...

    hutool-all-5.8.14

    StrUtil是Hutool的字符串处理工具类,包含了大量的字符串操作方法,如切割、替换、格式化等。例如,`StrUtil.join(array, ",")`可以将数组元素用逗号连接成字符串,`StrUtil.isBlank(str)`则判断字符串是否为空。 ...

    Hutool (Java基础工具类).zip

    这个压缩包“Hutool (Java基础工具类).zip”包含了关于Hutool库的相关资料,如使用说明和可能的示例代码。 首先,Hutool的命名来源于“实用”和“工具”的英文单词"Util",它由多个模块组成,涵盖了日期时间处理、...

    Hutool 参考文档.pdf

    核心部分(Hutool-core)包含了多个工具类,它们覆盖了克隆、类型转换、日期时间处理、IO流操作、资源访问、字符串处理、加密解密等各个方面,从而满足日常开发中的常见需求。 克隆部分提供了支持泛型的克隆接口和...

    webStrUtil2.0.jar源代码

    在源代码中,我们可能会看到如`StringUtil`这样的类,这是常见的工具类名称,用于封装各种字符串操作。例如,`StringUtil.isEmpty()`可能用于检查字符串是否为空或null,`StringUtil.trim()`则可能是用来去除字符串...

    基于Java的源码-常用工具包 Jodd.zip

    例如,Jodd提供了强大的字符串操作工具,如StrUtil,可以方便地进行字符串格式化、分割、替换等操作,极大地提高了代码的可读性和简洁性。 2. **Etc模块**: Etc模块包含了一些通用的配置和元数据处理工具。例如,...

    hutool-5-master_util工具大全_源码.zip

    2. **字符串处理**:StrUtil类包含大量字符串处理方法,如拼接、截取、替换、检查空值等,极大地提高了字符串操作的便捷性。 3. **文件操作**:FileUtil和PathUtil提供了文件和路径的创建、删除、复制、重命名等...

    hutool-5-master.zip

    4. **字符串处理**:StrUtil是Hutool中的字符串工具类,提供了大量的字符串处理方法,如格式化、拼接、截取、替换、校验等。 5. **加密解密**:EncryptUtil提供了常见的加密解密算法,如MD5、SHA、AES、DES等,便于...

    Hutool+Wiki.zip

    StrUtil是Hutool的字符串处理模块,包含了诸如字符串格式化、拼接、截取、查找替换、去除空格等常见操作。例如,StrUtil.isBlank()和StrUtil.isNotBlank()用于检查字符串是否为空,StrUtil.join()则可以方便地将数组...

    hutool-all-5.4.2_如何用hutool-all_hutoll_hutool-all_

    它集成了众多实用的工具类,覆盖了日期时间处理、字符串操作、文件操作、网络请求、加密解密、数据库操作等多个领域,旨在简化常见的开发任务,让开发者能够更加专注于业务逻辑的实现。 1. **日期时间处理**:...

    Hutool的api等可参考的文档

    - **字符串工具**:`StrUtil`提供了大量的字符串处理方法,如拼接、截取、替换等。 - **十六进制工具**:`HexUtil`用于进行十六进制的转换操作。 - **URL工具**:`URLUtil`处理URL相关操作,如解析、构建等。 - ...

    hutool-v5-master.zip

    1. **全面的工具集**:Hutool提供了丰富的工具类,涵盖了日期时间、字符串处理、文件操作、网络通信、加密解密、数学计算、集合操作等多个方面,大大减少了开发者编写基础代码的工作量。 2. **函数式编程风格**:...

    dromara-hutool-v5-master.zip

    `StrUtil`类中的静态方法展示了如何利用StringBuilder优化字符串操作,提高性能。`FileUtil`类的实现则让我们了解了文件操作背后的细节,包括错误处理和资源释放。 此外,Hutool还引入了SLF4J作为日志框架,提供了...

Global site tag (gtag.js) - Google Analytics