项目中要输出满多少字要换行,由于中文和英文占的位数不同,并且有的后面添加\n,有的是</br>,所以就自己写了一下工具类,保证输出的每行宽度相同。英文字符和符号占一位,中文和全角标点占2位
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
/**
*
* desc: string格式化输出换行工具
*
* @author <a href="mailto:yourmail">Hegege</a>
* @version CVS $Revision: 1.1 $ $Date: 2005/12/05 08:42:21 $
*/
public class StringFormatPrintUtil {
public static final String FSLP_RS_STRING = "string";
public static final String FSLP_RS_TEXT = "text";
public static String subString(String text, int length, String endWith) {
int textLength = text.length();
int byteLength = 0;
StringBuffer returnStr = new StringBuffer();
for (int i = 0; i < textLength && byteLength < length * 2; i++) {
String str_i = text.substring(i, i + 1);
if (str_i.getBytes().length == 1) {// 英文
byteLength++;
} else {// 中文
byteLength += 2;
}
returnStr.append(str_i);
}
try {
if (byteLength < text.getBytes("GBK").length) {// getBytes("GBK")每个汉字长2,getBytes("UTF-8")每个汉字长度为3
returnStr.append(endWith);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return returnStr.toString();
}
public static Map formatStringLnPlus(String text,int length,String endWith){
Map rs = new HashMap();
StringBuffer ss = new StringBuffer();
//输入的文本长度
int textLength = text.length();
//总字节长度
int byteLength = 0;
//定位指针
int p = -1;
//是否差半位
boolean k = false;
for(int i=0;i<textLength;i++){
String str_i = text.substring(i, i + 1);
if (str_i.getBytes().length == 1) {// 英文
byteLength++;
if(byteLength>length&&p<0){
p = i-1;
k=false;
}else if(byteLength==textLength&&p<0){
p = i;
k=false;
}
} else {// 中文
byteLength += 2;
if(byteLength>length&&p<0){
p = i-1;
k=true;
}else if(byteLength==textLength&&p<0){
p = i;
k=true;
}
}
}
if(byteLength<length){
//小于,要补全
ss.append(text);
for(int i = byteLength;i<length;i++){
ss.append(endWith);
}
text = "";
}else if(byteLength==length){
//等于,完整输出
ss.append(text);
text = "";
}else{
//超出,要截取
for(int i=0;i<p;i++){
String str_i = text.substring(i, i + 1);
ss.append(str_i);
}
text = text.substring(ss.toString().length());
if(k){
ss.append(endWith);
}
}
rs.put(FSLP_RS_STRING, ss.toString());
rs.put(FSLP_RS_TEXT, text);
return rs;
}
}