全角字符串的截取方法

公司做的是日本人项目,平时经常需要对一些字符串的值进行指定位数的截取,里面又经常是一些全角、半角混合的类型,当截不予到指定位数刚好是一个全角时,就不得不考虑怎么处理了,通常是少截取一位,将全角以后的全去掉。
所以,每次用到每次都要找老的项目,比较烦琐,还好最近不是太忙,赶快整理一下,方便以后使用。
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();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值