java格式化字符串,在指定位置插入指定字符串,兼容中英文以及特殊字符,例如:换行,用于解决生成pdf换行问题等问题

原因: 由于html转pdf时,不能自动换行,因此才有下面的代码.

 注释:完全模拟html页面的自动换行!

复制代码
package test;

import java.io.UnsupportedEncodingException;

/**
 * 解决pdf换行问题,在指定位置插入指定字符串,兼容中英文以及特殊字符
 * 
 * @author xg君
 * 
 */
public class app {

    public static void main(String[] args) throws UnsupportedEncodingException {
        System.out.println(addStr(10, "<br/>", "as阿萨德dsa阿斯蒂芬fladadasdsjf阿斯蒂芬ljdsljkjlfdsklfd啥地方都是skljdsasfasdfads"));
    }

    /**
     * 插入方法
     * 
     * @param num
     *            每隔几个字符插入一个字符串
     * @param splitStr
     *            待指定字符串
     * @param str
     *            原字符串
     * @return 插入指定字符串之后的字符串
     * @throws UnsupportedEncodingException
     */
    public static String addStr(int num, String splitStr, String str) throws UnsupportedEncodingException {
        StringBuffer sb = new StringBuffer();
        String temp = str;

        int len = str.length();
        while (len > 0) {
            int idx = getEndIndex(temp, num);
            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;
    }
}
复制代码

效果:

我的另一篇文章的地址:http://www.cnblogs.com/king-xg/p/6370890.html

 签名:雪糕君



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值