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;
        }
    
    }

    //

  • 相关阅读:
    剑指offer-重建二叉树
    Java集合学习-总体框架
    leetcode-6-ZigZag Conversion
    海拔高度与大气密度的关系函数
    C++ 获取文件夹下的所有文件名
    01-复杂度1. 最大子列和问题
    00-自测5. Shuffling Machine
    00-自测4. Have Fun with Numbers
    00-自测3. 数组元素循环右移问题
    00-自测2. 素数对猜想
  • 原文地址:https://www.cnblogs.com/woshuaile/p/11995057.html
Copyright © 2011-2022 走看看