
课程咨询: 400-996-5531 / 投诉建议: 400-111-8989
认真做教育 专心促就业
昆明达内培训的小编给大家讲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;
}
}
了解详情请登陆昆明达内IT培训官网(km.tedu.cn)!