按照字节数截取一个字符串,“abc你好” 如果截取到半个中文,舍弃,比如 截取4个字节 abc。截取 5个字节abc你

来源:互联网 发布:手机视频保密软件 编辑:程序博客网 时间:2024/05/17 07:23
import java.io.IOException;import java.io.UnsupportedEncodingException;public class Test {/** * @param args * @throws IOException  */public static void main(String[] args) throws IOException {/* *  按照字节数截取一个字符串,“abc你好” 如果截取到半个中文,舍弃,比如 截取4个字节 abc。截取  5个字节abc你 *  定义功能实现 *  字符串-->字节数组  编码 *  字节数组-->字符串。 解码。 *   GBK2312编码的一个中文是两个字节,而且两个字节的最高位都是1,也就是说是一个负数  *  思路: *    1, 中文两个字节都是负数 *    2,判断截取的最后一个字节是否是负数 *     如果不是,直接截取 *      如果是,就往回判断前一个是否是负数,并记录负数的个数,如果连续的负数有奇数个,舍弃最后一个字节 *       如果连续的负数是偶数个,不舍弃 */String str="abc你好"; byte[] buf= str.getBytes("GBK");         for(int x=0;x<buf.length;x++)      {   String temp= cutStringByCount(str,x+1);   System.out.println(temp);      }      }private static String cutStringByCount(String str, int len) throws IOException {byte[] buf= str.getBytes("GBK");int count=0;for(int x=len-1;x>=0;x--){if(buf[x]<0){count++;}else { break;}}if(count%2==0){return new String(buf,0,len);}else{return new String(buf,0,len-1);}}}

1 0