java 按字节长度_Java按字节数截取字符串,一个中文长度为2

碰到可能会截取汉字的情况,当然是要不能截取出乱码来,就是不能对整个汉字截取一半。如"我ABC汉字d"这个字符串,截取5个字节的时候,应该是"我

ABC",而截取8个字节的时候,应该是"我ABC汉",而不应该是"我ABC汉?",其中"?"为半个汉字,可理解为向前截取public static String subStr(String str, int subSLength)

throws UnsupportedEncodingException{

if (str == null)

return "";

else{

int tempSubLength = subSLength;//截取字节数

String subStr = str.substring(0, str.length()

int subStrByetsL = subStr.getBytes("GBK").length;//截取子串的字节长度

//int subStrByetsL = subStr.getBytes().length;//截取子串的字节长度

// 说明截取的字符串中包含有汉字

while (subStrByetsL > tempSubLength){

int subSLengthTemp = --subSLength;

subStr = str.substring(0, subSLengthTemp>str.length() ? str.length() : subSLengthTemp);

subStrByetsL = subStr.getBytes("GBK").length;

//subStrByetsL = subStr.getBytes().length;

}

return subStr;

}

}

备注:将字符编码GBK改为UTF-8,则每个中文长度按3个字符计算

以下方法是向后截取字符串public static String subStr_1(String str, int start, int end)

throws UnsupportedEncodingException{

if (str == null)  return null;

String chinese = "[\u0391-\uFFE5]";

byte[] b = str.getBytes("UTF-8");

String temp = new String(b, start, end);

String last = getLastStr(temp);

while(!last.matches(chinese)){

temp = new String(b, start, ++end);

last = getLastStr(temp);

}

return new String(b, start, end);

}

public static String getByteStr(String str, int start, int end) throws UnsupportedEncodingException{

byte[] b = str.getBytes("UTF-8");

return new String(b, start, end);

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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, 你"。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值