按 字节截取分别以GBK 和 utf-8 编码的 字符串的java程序。

本文提供了一个Java程序示例,展示了如何根据指定字节数截取包含中英文混合文本的字符串,并确保截取后的字符串保持字符的完整性和可读性。通过使用GBK和UTF-8两种不同的编码方式,该示例解释了如何正确处理不同长度的汉字编码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package Other;

import java.io.IOException;

public class CutByteDemo {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {

		String s= "hello你好啊,我欣賞你hahah";
		byte []buf = s.getBytes("GBK");
		
		for(int i =1;i<=buf.length;i++){
			System.out.println("截取"+i+"个字节后为"+cutByteByGBK(buf,i));
		}
		buf = s.getBytes("utf-8");
		for(int i =1;i<=buf.length;i++){
			System.out.println("截取"+i+"个字节后为"+cutByteByU8(buf,i));
		}
	}

	public static String cutByteByU8(byte[] buf, int j) throws IOException {
		int count = 0; 
		int i =0;
		for(i = j-1 ; i >= 0 ; i--){
			if(buf[i]<0)
				count++;
			else
				break;			
		}
		String s =null;
		//因為UTF-8三個字節表示一個漢字
		if(count%3 == 0)
			s =new String(buf,0,j,"utf-8");
		else if(count%3 == 1)
			s= new String(buf,0,j-1,"utf-8");
		else if(count%3 == 2)
			s= new String(buf,0,j-2,"utf-8");
		return s;
	}

	public static String cutByteByGBK(byte[] buf, int j) throws IOException {
		int count = 0; 
		
		int i =0;
		for(i = j-1 ; i >= 0 ; i--){
			if(buf[i]<0)
				count++;
			else
				break;			
		}
		String s =null;
		//因為GBK用兩個字節表示一個漢字
		if(count%2 == 0)
			s =new String(buf,0,j,"GBK");
		else
			s= new String(buf,0,j-1,"GBK");
		return s;
	}
}


结果:

截取1个字节后为h
截取2个字节后为he
截取3个字节后为hel
截取4个字节后为hell
截取5个字节后为hello
截取6个字节后为hello
截取7个字节后为hello你
截取8个字节后为hello你
截取9个字节后为hello你好
截取10个字节后为hello你好
截取11个字节后为hello你好啊
截取12个字节后为hello你好啊
截取13个字节后为hello你好啊,
截取14个字节后为hello你好啊,
截取15个字节后为hello你好啊,我
截取16个字节后为hello你好啊,我
截取17个字节后为hello你好啊,我欣
截取18个字节后为hello你好啊,我欣
截取19个字节后为hello你好啊,我欣賞
截取20个字节后为hello你好啊,我欣賞
截取21个字节后为hello你好啊,我欣賞你
截取22个字节后为hello你好啊,我欣賞你h
截取23个字节后为hello你好啊,我欣賞你ha
截取24个字节后为hello你好啊,我欣賞你hah
截取25个字节后为hello你好啊,我欣賞你haha
截取26个字节后为hello你好啊,我欣賞你hahah
截取1个字节后为h
截取2个字节后为he
截取3个字节后为hel
截取4个字节后为hell
截取5个字节后为hello
截取6个字节后为hello
截取7个字节后为hello
截取8个字节后为hello你
截取9个字节后为hello你
截取10个字节后为hello你
截取11个字节后为hello你好
截取12个字节后为hello你好
截取13个字节后为hello你好
截取14个字节后为hello你好啊
截取15个字节后为hello你好啊
截取16个字节后为hello你好啊
截取17个字节后为hello你好啊,
截取18个字节后为hello你好啊,
截取19个字节后为hello你好啊,
截取20个字节后为hello你好啊,我
截取21个字节后为hello你好啊,我
截取22个字节后为hello你好啊,我
截取23个字节后为hello你好啊,我欣
截取24个字节后为hello你好啊,我欣
截取25个字节后为hello你好啊,我欣
截取26个字节后为hello你好啊,我欣賞
截取27个字节后为hello你好啊,我欣賞
截取28个字节后为hello你好啊,我欣賞
截取29个字节后为hello你好啊,我欣賞你
截取30个字节后为hello你好啊,我欣賞你h
截取31个字节后为hello你好啊,我欣賞你ha
截取32个字节后为hello你好啊,我欣賞你hah
截取33个字节后为hello你好啊,我欣賞你haha
截取34个字节后为hello你好啊,我欣賞你hahah

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值