字节--编程题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30625315/article/details/83656966

编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串, 但要保证汉字不被截取半个,如“我 ABC”,4,应该截取“我 AB”,输入“我 ABC 汉 DEF”,6,应该输出“我 ABC”,而不是“我 ABC+汉的半个”。


思路:
– utf-8中,一个字母用一个字节表示,一个汉字用三个字节表示,特殊的汉字用四个字节表示;
– gbk中,一个字母用一个字节表示,一个汉字用两个字节表示。
– 字母的字节编码> 0
– 汉字的字节编码< 0
附一个ASCII码对照表【http://tool.oschina.net/commons?type=4】
和一个字符编码查询表【http://www.mytju.com/classcode/tools/encode_utf8.asp】

	public static void main(String[] args) throws UnsupportedEncodingException {
		String str = "嗨hello你好";
		int bytenum = 8;
		System.out.println(cutString(str,bytenum ));
	}
	
	public static String cutString(String str, int bytenum ) throws UnsupportedEncodingException{
		byte[] bytes = str.getBytes("GBK");
		int num = charnum(bytes,bytenum );
		String subStr = str.substring(0,num);
		return subStr;
	}
	
	public static int charnum(byte[] buf,int bytenum){
		int num = 0;
		boolean bChineseFirstHalf = false;
		for(int i=0; i<bytenum ; ++i){
			if(buf[i]<0 && !bChineseFirstHalf){
				bChineseFirstHalf= true;
			}else{
				num++;
				bChineseFirstHalf= false;
			}
		}
		return num;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_30625315/article/details/83656966