zoukankan      html  css  js  c++  java
  • 字符串换行工具类/每隔几位插入指定字符串

    package com.grandcanal.ifcs.utils;
    
    import java.io.UnsupportedEncodingException;
    
    /**
     * 字符串换行工具类/每隔几位插入指定字符串
     * @author kuangQingLin
     * @version 1.0
     * @date 2019/12/6/006 14:03
     **/
    public class NewLineUtil {
    
        /**
         * 插入方法
         *
         * @param num      每隔几个字符插入一个字符串(中文字符)
         * @param splitStr 待指定字符串
         * @param str      原字符串
         * @return 插入指定字符串之后的字符串
         * @throws UnsupportedEncodingException
         */
        public static String addStr(int num, String splitStr, String str)  {
            StringBuffer sb = new StringBuffer();
            String temp = str;
            int len = str.length();
            while (len > 0) {
                int idx = 0;
                try {
                    idx = getEndIndex(temp, num);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                sb.append(temp.substring(0, idx + 1)).append(splitStr);
                temp = temp.substring(idx + 1);
                len = temp.length();
            }
            return sb.toString();
        }
    
    
        /**
         * 两个数字/英文
         *  两个数字或者字母等同于一个汉汉字的长度
         * @param str 字符串
         * @param num 每隔几个字符插入一个字符串
         * @return int 最终索引
         * @throws UnsupportedEncodingException
         */
        public static int getEndIndex(String str, double num) throws UnsupportedEncodingException {
            int idx = 0;
            double val = 0.00;
            // 判断是否是英文/中文
            for (int i = 0; i < str.length(); i++) {
                if (String.valueOf(str.charAt(i)).getBytes("UTF-8").length >= 3) {
                    // 中文字符或符号
                    val += 1.00;
                } else {
                    // 英文字符或符号
                    val += 0.50;
                }
                if (val >= num) {
                    idx = i;
                    if (val - num == 0.5) {
                        idx = i - 1;
                    }
                    break;
                }
            }
            if (idx == 0) {
                idx = str.length() - 1;
            }
            return idx;
        }
    
    }

    //

  • 相关阅读:
    死锁篇
    java线程池
    sql server 多行数据指定字符串拼接
    动态提交 表格
    ABP
    DDD学习
    sql 语句插入数据返回id
    Post方式提交,通过上下文HttpContext,Request[""]获取
    JQ的过滤隐藏
    sql 查询有多少行
  • 原文地址:https://www.cnblogs.com/woshuaile/p/11995057.html
Copyright © 2011-2022 走看看