问题
需求:给定一个中英文字符串,截取固定长度后存储数据 情况:中文占用2个字节,英文1个
//org.apache.commons.lang3.StringUtils.substring(columnVal, 0, lenMax)
public static String substring(String str, int start, int end) {
if (str == null) {
return null;
} else {
if (end end) {
return "";
} else {
if (start 字符长度============原始::测试
Test==>字符长度============4
Test==>字符长度============截取::测试
解决
/**
* 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1
*
* @param value
* @param length
* @return
*/
public static String getStringLengthBySub(String value, int length) {
//String str, int start, int end
if (StringUtils.isBlank(value)) {
return value;
}
String chinese = "[\u0391-\uFFE5]";
int tc = 1;
int s = 0;
String str = "";
/* 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1 */
while (tc 字符长度============4
Test==>字符长度============原始::测试
Test==>字符长度============2
Test==>字符长度============截取::测
参考
JAVA 中英文混合截取,中文算2字符,英文1字符,始终保持固定长度
|