截取字节数组形式的字符串,串中包含中文

描述

1、首先说一下各种字符的字节组成:

字符、字母和数字:由一个大于0的数字码组成,比如1--49、A--65、b--98。即这三种类型长度为1字节。

汉字:由两个小于0的数字码组成,比如 “我”-- (-50,-46)、“们”--(-61,-57)。即中文长度为2字节。

2、解释一下题干

输入是一个包含中文的字符串str,和一个截取长度i,要求把str截取i个字符长度输出,但是如果末尾是半个中文,就舍弃掉。因为除了汉字以外的其他都是1字节长度,所以本题难度是处理中文的问题。

代码

public void A(String str, int i){
		byte b[] = new byte[1024];
		int num = 0;
		b = str.getBytes();
		if(b[i-1]>0){
			System.out.println(new String(b, 0, i));
		}else {
			for(int j=0; j<i; j++){
				if(b[j]<0){
					num ++;
					num = num % 2;
				}else {
					num = 0;
				}
			}
			if(num == 0){
				System.out.println(new String(b, 0, i));
			}else {
				System.out.println(new String(b, 0, i-1));
			}
		}
	}

主函数:

public static void main(String[] args) {
		String str = "哈哈1Ab我们的田野";
		new testString().A(str, 10);
		
	}

输出:

哈哈1Ab我

主函数中要求截取输出10字节,那么“哈哈1Ab我”的字节长度为 2+2+1+1+1+2 = 9,而后边是一个汉字,也就是第10字节只是半个汉字,所以舍弃掉。

posted @ 2017-12-08 18:14  K_artorias  阅读(763)  评论(0编辑  收藏  举报