引入Hutool工具包,或者自己实现也行
<dependencyManagement>
<dependencies>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-bom</artifactId>
<version>${hutool.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
/**
* 截取部分字符串,这里一个汉字的长度认为是2
* @param str 字符串
* @param len 切割的位置
* @return 切割后的字符串
*/
public static String subFloorPreGbk(String str, int len) {
if (StrUtil.isEmpty(str)) {
return StrUtil.str(str);
}
if (str.getBytes(CharsetUtil.CHARSET_GBK).length <= len) {
return str;
}
byte[] bytes = new byte[len];
int idx = 0;
for (int i = 0; i < str.length(); i++) {
String s = str.substring(i, i + 1);
byte[] b = s.getBytes(CharsetUtil.CHARSET_GBK);
if (idx + b.length > len) {
break;
}
for (byte t : b) {
bytes[idx++] = t;
}
}
return new String(bytes, CharsetUtil.CHARSET_GBK);
}