package net.zhangji.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.zhangji.exception.MyException;
/**
* 字符串处理工具
*
* @author 张继
*
*/
public class StringUtil {
/**
* 判断字符串是否为空:null、""均为空
* 不允许空格:" "也为空
*
* @param str
需判断的字符串
* @param isExistSpace
是否允许存在空格
* @return
判断结果:true表示为空
*/
public static boolean isEmpty(String str, boolean isExistSpace) {
if(null == str)
//对象为空
return true;
if("".equals(str) || str.length() == 0)
//对象长度为0
return true;
if(!isExistSpace && "".equals(str.trim())){
//允许存在空格
return true;
}
return false;
}
/**
* 字符串过滤
*
* @param str
待过滤字符串
* @param reg
过滤格式
* @param replaceStr
替换的字符串
* @param type 2: 忽略大小写
1:全局匹配
* @return
过滤后的字符串
*/
public static String filterStr(String str, String replaceStr, String reg, Integer type) {
/*
* CASE_INSENSITIVE
忽略大小写
*/
Pattern pat = null;
if(type == 1)
pat = Pattern.compile(reg, Pattern.DOTALL);
if(type == 2)
pat = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
Matcher matcher = pat.matcher(str);
if(matcher.find()) {
str = matcher.replaceAll(replaceStr);
}
return str;
}
/**
* 字符串输出长度格式化
*
* @param str
输出格式化目标字符串
* @param beginIndex
开始位置
* @param length
截取长度
* @return
输出字符串
*/
public static String printFormat(String str, Integer beginIndex, Integer length) {
return str.substring(beginIndex, beginIndex+length) + "...";
}
/**
* 字符串分割为字符串数组
*
* @param str
* @param decollator
* @return
*/
public static String[] toArray(String str, String decollator) {
if(isEmpty(str, true) || isEmpty(decollator, true))
//验证字符串是否为空
return null;
if(str.lastIndexOf(decollator) == str.length() - 1) //需分割的字符串最后一个字符不能为分隔符
str = str.substring(0, str.length() - 1);
if(isEmpty(str, true) || isEmpty(decollator, true))
return null;
if(str.lastIndexOf(decollator) == 0)
//需分割的字符串第一个字符不能为分隔符
str = str.substring(1, str.length());
if(isEmpty(str, true) || isEmpty(decollator, true))
return null;
String[] array = null ;
if(str.indexOf(decollator) < 0) {
array = new String[1];
array[0] = str;
} else {
array = str.split(decollator);
}
return array;
}
/**
* 字符串分割并转化为整形数组
*
* @param str
需分割字符串
* @param decollator
分割字符
* @return
整形数组
*/
public static Integer[] toIntegerArray(String str, String decollator) {
String[] strArr = toArray(str, decollator);
if(null == strArr || strArr.length == 0)
return null;
Integer[] intArr = new Integer[strArr.length];
int j = 0;
for(int i = 0; i<strArr.length; i++) {
try {
intArr[j] = Integer.parseInt(strArr[i]);
j++;
} catch (Exception e) {
// TODO: handle exception
new MyException("String to Integer exception").printStackTrace();
}
}
if(j == intArr.length)
return intArr;
Integer[] targetArr = new Integer[j];
for(int i = 0; i<j; i++) {
targetArr[i] = intArr[i];
}
return targetArr;
}
}