• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
学习记录
博客园    首页    新随笔    联系   管理    订阅  订阅
JAVA实现中英文混合文字友好截取功能
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;
    }
}

posted on 2021-09-14 16:52  abspace  阅读(302)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3