JAVA按指定的字节数截取字符串

	/**
	 * 按指定的字节数截取字符串(一个中文字符占3个字节,一个英文字符或数字占1个字节)
	 * @param sourceString 源字符串
	 * @param cutBytes 要截取的字节数
	 * @return
	 */
	public static String cutString(String sourceString, int cutBytes)
	{
		if(sourceString == null || "".equals(sourceString.trim()))
		{
			return "";
		}
		
		int lastIndex = 0;
		boolean stopFlag = false;
		
		int totalBytes = 0;
		for(int i=0; i<sourceString.length(); i++)
		{
			String s = Integer.toBinaryString(sourceString.charAt(i));
			if(s.length() > 8)
			{
				totalBytes += 3;
			}
			else
			{
				totalBytes += 1;
			}
			
			if(!stopFlag)
			{
				if(totalBytes == cutBytes)
				{
					lastIndex = i;
					stopFlag = true;
				}
				else if(totalBytes > cutBytes)
				{
					lastIndex = i - 1;
					stopFlag = true;
				}
			}
		}
		
		if(!stopFlag)
		{
			return sourceString;
		}
		else
		{
			return sourceString.substring(0, lastIndex + 1);
		}
	}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java中,字符串字节截取遇到汉字的情况需要特别处理。一般而言,一个汉字占据两个字节的存储空间。为了正确处理汉字在字符串中的截取,可以使用Java的String类中的getBytes()方法来获取字符串字节数组,然后根据字节数组的长度进行截取。 具体的做法是,首先将字符串转换为字节数组,然后遍历字节数组,统计字节数,直到达到指定截取长度。需要注意的是,若截取的最后一个字符正好是半个汉字,要将其舍弃,以保证截取后的字符串是完整的。最后,再将字节数组转换为字符串,即可得到按字节截取后的字符串。 下面是一个示例代码: ```java public static String subStringByBytes(String str, int limit) { byte[] bytes = str.getBytes(); int length = bytes.length; if (limit >= length) { return str; } int count = 0; for (int i = 0; i < limit; i++) { if ((bytes[i] & 0xFF) > 128) { count++; } } if (count % 2 != 0) { limit = limit - 1; } return new String(bytes, 0, limit); } public static void main(String[] args) { String str = "Hello, 你好!"; String newStr = subStringByBytes(str, 9); System.out.println(newStr); // 输出:Hello, 你 } ``` 在以上代码中,定义了一个`subStringByBytes`方法,该方法接受一个字符串和一个限制的字节数作为参数,并返回按字节截取后的字符串。在示例中,将字符串"Hello, 你好!"按字节截取9个字节长度,结果为"Hello, 你"。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值