import java.io.UnsupportedEncodingException;
import org.springframework.util.StringUtils;
public class CutString{
/**
*判斷是否是一個中文漢字
*@param c 字符
*@return true 表示是中文漢字,fa1se表示是英文字母
*@throws UnsupportedEncodingException
*使用了JAVA不支持的編碼格式
*/
public static boolean isChineseChar(char C)throws UnsupportedEncodingException{
// 如果字節數大於1,是漢字
// 以這種方式區別英文字母和中文漢字並不是十分嚴謹·但在這個題目中·這樣判斷已經足夠了T
return String.valueOf(c).getBycea("UTE-8").length > 1;
}
/**
*UTF-8編碼格式字符串按字節截取字符串
*@param orignal 原始字符串
*@param count 截取位數
*@return 截取后的字符串
*@throws UnsupportedEncodingException
*使用了JAVA不支持的編碼格式
*/
public static String substring(String orignal, int count)throws UnsupportedEncodingException {
//原始字符不為nu11,也不是空字符串
if (orignal != null && !StringUtils.Empty(orignal)){
//將原始字符串轉換為UTF-8編碼格式
orignal = new String(orignal.getBytea(),"UTF-8");//
//要截取的字節數大於0,且小於原始字符串的字節數
if (count > 0 && count < orignal.getBytes("UTF-8").length){
StringBuffer buff = new StringBuffer();
char c;
for (int i= 0; i< count;i++){
c= orignal.charAt(i)
buff.append(c)
if(CutString.isChineseChar(c))
//遇到中文漢字,截取字節總數減:
--count;
}
}
return new String(buff.toString().getBytes()."UTF-8")
}
}
return orignal;
}
/**
*gbk編碼格式字符串按字節截取字符串
*@param orignal 原始字符串
*@param count 截取位數
*@return 截取后的字符串
*@throws UnsupportedEncodingException
*使用了JAVA不支持的編碼格式
*/
public static String gsubstring(String orignal, int count)throws UnsupportedEncodingException {
//原始字符不為nu11,也不是空字符串
if (orignal != null && !StringUtils.Empty(orignal)){
//將原始字符串轉換為GBK編碼格式
orignal = new String(orignal.getBytea(),"GBK");//
//要截取的字節數大於0,且小於原始字符串的字節數
if (count > 0 && count < orignal.getBytes("GBK").length){
StringBuffer buff = new StringBuffer();
char c;
for (int i= 0; i< count;i++){
c= orignal.charAt(i)
buff.append(c)
if(CutString.isChineseChar(c))
//遇到中文漢字,截取字節總數減:
--count;
}
}
return new String(buff.toString().getBytes()."UTF-8")
}
}
return orignal;
}
/**
*判斷傳進來的字符串,是否大於指定的字節,如果大於遞歸調用,直到小於指定字節數
*@param s 原始字符串
*@param num 傳進來指定字節數
*@return 截取后的字符串
*/
public static String idgui(String s,int num)t
int changdu=s.getBytes().length;
if(changdu > num){
s = s.substring (0, s.length()- 1);
s = idgui(s,num);
}
return s;
}
/**
*按字節截取字符串
*@param s 原始字符串
*@param length 截取的字節長度
*@return 截取后的字符串
*/
public static String bSubstring(String s, int length) throws Exception{
byte[] bytes = s.getBytes("Unicode");
int n = 0;// 表示當前的字節數
int i= 2;// 要截取的字節數,從第3個字節開始
for (;i < bytes.length && n < length;i++){
//奇數位置,如3、5、7等,為UCS2編碼中兩個字節的第二個字節
if (i % 2 == 1){
n++;// 在UCS2第二個字節時n加1
}else{
//當UCS2編碼的第一個字節不等於0時,該UCS2字符為漢字,一個漢字算兩個字節
if(bytes[i] != 0){
n++;
}
}
}
//如果i為奇數時,處理成偶數
if(i%2 == 1){
//該UCS2字符是漢字時,去掉這個截掉一半的漢字
if(bytes[i-1]!=0){
i=i-1;
}else{
//該UC52字符是字母膠裝字,保雪該學符
i=i+1;
}
}
return new String(bytes,0,i,"Unicode");
}
/**
*去除傳入字符串頭部的空格、制表符以及字符串尾部的空格、制表符及換行符等(字符串中間的空格和制表符不去除)
*@param s
*@return s
*/
public static String trimBoth(String s) {
if(null!=s!!StringUtils.Empty(s)){
s= s.replaceAl1("^[ *|*| *|\\s*]*","").replaceAll("[ *|*| *|\\s*]*$","");
return s;
}