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

来源:互联网 发布:hadoop2.7.3源码下载 编辑:程序博客网 时间:2024/05/17 02:23

原因: 由于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

 签名:雪糕君



0 0
原创粉丝点击