java按照字节截取字符串

在Java中,我们经常遇到的一个问题就是截取字符串。

public static void main(String[] args) {
		String str="我爱java";
		System.out.println(str.substring(0, 2));
	}


运行这行代码,我们可以知道,控制台输出的是:我爱

有些时间,这种截取方法不可取。比如:在Oracle数据库中,字段大小为varchar2(10),这个是这个字段最大能保存10个字节的字符串。我们如果这么写,那等待的就是报错了

 

	public static void main(String[] args) {
		String str="测试小酱油啊,我是来测试的。";
		System.out.println(str.substring(0, 10));
	}

我们知道在GBK下,汉字是占两个字节,UTF-8下汉字是占三个字节,所以,这个截取只能按照字节来截取了。

现在我们又有一个疑问,一个汉字占三个字节,如果我只要10个字节,那么4个汉字是12个字节最后一个汉字只截取了一般,导致乱码。所以我们在截取的时间相对的处理下。

见代码:ps在网上找了个代码,大家参考下,本人语文不好,见谅。

<pre class="java" name="code">package cn.ztz.test;

public class Test {
	public static void main(String[] args)throws Exception {
		String str = "测试小酱油啊,我是来测试的";
		System.out.println(subStringByByte(str,10));
	}

	private static String subStringByByte(String str, int len)throws Exception {
		String result = null;
		if (str != null) {
			byte[] a = str.getBytes("UTF-8");
			if (a.length <= len) {
				result = str;
			} else if (len > 0) {
				result = new String(a, 0, len);
				int length = result.length();
				if (str.charAt(length - 1) != result.charAt(length - 1)) {
					if (length < 2) {
						result = null;
					} else {
						result = result.substring(0, length - 1);
					}
				}
			}
		}
		return result;
	}
}

 


 

运行这个代码,控制台输出:测试小

UTF-8下,三个汉字正好9个字节。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值