首先明确一点字节长度和字符长度是不同的两个概念,举个例子。 “测试截取helloworld”, 字符长度:14,1个文字代表1个字符,1个字母代表1个字符, UTF-8格式下的字节长度:26,1个文字代表4个字节,1个字母代表1个字节, GBK格式下的字节长度:18,1个文字代表2个字节,1个字母代表1个字节。 java中的substring()方法就是根据字符串的字符长度截取的,接下来上代码
package com.test;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.UnsupportedEncodingException;
@SpringBootTest
public class Test1 {
@Test
public void test1(){
String payment = "测试截取helloworld";
try{
System.out.println(substringByte(payment,0,2));
System.out.println(substringByte(payment,0,4));
System.out.println(substringByte(payment,0,6));
System.out.println(substringByte(payment,0,8));
System.out.println(substringByte(payment,0,9));
System.out.println(substringByte(payment,8,10));
}catch (Exception e){
e.printStackTrace();
}
}
/**
*
* @param orignal 要截取的字符串
* @param start 开始下标
* @param count 截取长度
* @return
*/
public static String substringByte(String orignal, int start, int count) {
// 如果目标字符串为空,则直接返回,不进入截取逻辑;
if (orignal == null || "".equals(orignal)){
return orignal;
}
// 截取Byte长度必须>0
if (count
start = 0;
}
// 目标char Pull buff缓存区间;
StringBuffer buff = new StringBuffer();
try {
// 截取字节起始字节位置大于目标String的Byte的length则返回空值
if (start >= getStringByteLenths(orignal)) {
return null;
}
int len = 0;
char c;
// 遍历String的每一个Char字符,计算当前总长度
// 如果到当前Char的的字节长度大于要截取的字符总长度,则跳出循环返回截取的字符串。
for (int i = 0; i
len += String.valueOf(c).getBytes("GBK").length;
if (len
break;
}
} else {
// 截取字符串从非0位置开始
len += String.valueOf(c).getBytes("GBK").length;
if (len > start && len
break;
}
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 返回最终截取的字符结果;
// 创建String对象,传入目标char Buff对象
return new String(buff);
}
public static int getStringByteLenths(String args) throws UnsupportedEncodingException {
return args != null && args != "" ? args.getBytes("GBK").length : 0;
}
}
以上代码设置的编码格式为GBK,输出结果为下图
|