1. 程式人生 > >java格式化字串,在指定位置插入指定字串,相容中英文以及特殊字元,例如:換行,用於解決生成pdf換行問題等問題

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; } }
複製程式碼

效果:

簽名:雪糕君