public class SubStringTest {
/**
*
* @param src 源字符串
* @param subLength 需要截取的长度
* @return
*/
public static String subString(String src, int subLength) {
if(src == null){
return null;
}
if(subLength == 0){
return "";
}
StringBuffer sb = new StringBuffer();
char[] chars = src.toCharArray();
for (char a : chars) {
if (isContinueAppend(sb, a, subLength)) {
sb.append(a);
}
else{
break;
}
}
return sb.toString();
}
/**
*
* @param sb 已截到的字符串
* @param a 当前要被装进sb的字符
* @param subLength 需要截取的长度
* @return
*/
public static boolean isContinueAppend(StringBuffer sb, char a,
int subLength) {
int currentLength = 0;
for (char temp : sb.toString().toCharArray()) {
currentLength += (temp >> 8 == 0) ? 1 : 2;
}
return (currentLength + (a >> 8 == 0 ? 1 : 2)) <= subLength;
}
public static void main(String[] args) {
System.out.println(subString("我是一a个中国人",7));
}
}
截取字符串 中文按两个字符长度处理情况
最新推荐文章于 2021-12-12 14:31:03 发布