您的位置:首页 > 其它

字符串截取(按指定的字节数)汉字不可以截取半个

2012-09-22 20:47 316 查看
package com.interview.demo;

/**

* 截取字符串 按指定的字节数

* 汉子不可截取半个 abc中国人 4 输出:abc 而不是abc+半个人

*/

import java.io.UnsupportedEncodingException;

public class WhiltCat{

public static boolean isChinese(char ch) throws UnsupportedEncodingException{

return String.valueOf(ch).getBytes("GBK").length>1;

}

public static String cutString(String str,int count) throws UnsupportedEncodingException{

if(str!=null&&!"".equals(str)){

str = new String(str.getBytes(),"GBK");

if(count>0&&count<str.getBytes("GBK").length){

StringBuffer buf = new StringBuffer();

char c;

int num = 0;

for(int i=0;i<str.length()-1;i++){

c = str.charAt(i);

//从头扫描每个字符 首先判断是不是汉子 接着判断当前截取的字节数+2是否超过了要截取的字节数,

//如果超过舍弃截取此汉字;否则加入;

//

if(isChinese(c)){

if(num+2<=count){

buf.append(c);

num = num+2;

}else{

break;

}

}else{

if(num+1<=count){

buf.append(c);

num=num+1;

}else{

break;

}

}

}

return buf.toString();

}

}

return str;

}

public static void main(String[] args){

String str = "到遇到jfr是中hinese";

try {

System.out.println(cutString(str,7));

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐