java hutool 如何判断字符串中是否存在非GBK编码的字符如果存在就将它们转换为unicode
可以使用Hutool中的CharsetType类和UnicodeUtil类,代码如下:
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.UnicodeUtil;
public class Test {
public static void main(String[] args) {
String str = "测试字符串abc";
String charset = CharsetUtil.GBK;
boolean hasNonGBK = StrUtil.containsIgnoreCase(str, charset);
if (hasNonGBK) {
str = UnicodeUtil.toUnicode(str);
}
System.out.println(str);
}
}
首先使用StrUtil.containsIgnoreCase()方法判断字符串中是否包含GBK编码中不存在的字符,如果存在则将整个字符串转换为unicode编码
原文地址: https://www.cveoy.top/t/topic/fq7F 著作权归作者所有。请勿转载和采集!