全角字符串的截取方法

公司做的是日本人项目,平时经常需要对一些字符串的值进行指定位数的截取,里面又经常是一些全角、半角混合的类型,当截不予到指定位数刚好是一个全角时,就不得不考虑怎么处理了,通常是少截取一位,将全角以后的全去掉。
所以,每次用到每次都要找老的项目,比较烦琐,还好最近不是太忙,赶快整理一下,方便以后使用。
public static String fromatStringRightJIS(String strSource, int len){
if(LengthFormat.stringLength(strSource)>len){
String retStrTmp=LengthFormat.formatString(strSource,len+1);
if(LengthFormat.stringLength(retStrTmp.substring(retStrTmp.length()-1,retStrTmp.length()))>=2)
return LengthFormat.formatString(strSource,len-1);
else
return LengthFormat.formatString(strSource,len);
}else
return LengthFormat.formatString(strSource,len);
}
public static int stringLength(String strSource) {
StringBuffer strBuffer = new StringBuffer("");
if (strSource == null || strSource.equals("")) {
return 0;
} else {
try {
byte[] tmpBytes = strSource.concat(strBuffer.toString()).getBytes("SJIS");
return tmpBytes.length;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return 0;
}
public static String formatString(String strSource, int len) {
String rt = "";
StringBuffer strBuffer = new StringBuffer("");
for (int i = 0; i < len; i++) {
strBuffer.append(" ");
}
if (strSource == null || strSource.equals("")) {
rt = strBuffer.toString();
} else {
try {
byte[] tmpBytes = strSource.concat(strBuffer.toString()).getBytes("SJIS");
rt = new String(tmpBytes, 0, len, "Shift_JIS");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return rt.toString();
}

你可能感兴趣的:(全角字符串的截取方法)