JAVA实现中英文混合文字友好截取功能

2023-03-13,,

package com.xxx.utils;

import com.google.common.collect.Lists;

import java.util.List;

/**
* 字符工具类
*/
public final class CharUtil { public CharUtil() {
} /**
* 实际字符串分隔
* @param charStr 需要分隔的字符串
* @param catIndex 分隔长度
* @return List
*/
private static String[] cut(String charStr,int catIndex){
String sb = "";
int charLength = 0;
for (int i = 0;i<charStr.length() ;i++ ){
int asciiCode = charStr.codePointAt(i);
if (asciiCode >=0 && asciiCode<=255){
charLength+=1;
} else{
charLength+=2;
}
if (charLength<=catIndex) {
sb += charStr.charAt(i);
}else{
break;
}
}
return new String[]{charStr.substring(sb.length()),sb};
} /**
* 把字符串按照字符的长度进行分隔
* @param charStr 需要分隔的字符串
* @param catIndex 分隔长度
* @return List
*/
public static List<String> cutString(String charStr, int catIndex){
List<String> result = Lists.newArrayList();
boolean endCond = true;
while (endCond){
String[] forCutChar = cut(charStr, catIndex);
result.add(forCutChar[1]);
if(forCutChar[0].length() > catIndex){
charStr = forCutChar[0];
}else{
endCond = false;
if(StringUtil.isNotBlank(forCutChar[0])){
result.add(forCutChar[0]);
}
}
}
return result;
}
}

JAVA实现中英文混合文字友好截取功能的相关教程结束。

《JAVA实现中英文混合文字友好截取功能.doc》

下载本文的Word格式文档,以方便收藏与打印。