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

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);
		}
		
	}
	}



发布了56 篇原创文章 · 获赞 14 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章