string 格式化输出工具类

项目中要输出满多少字要换行,由于中文和英文占的位数不同,并且有的后面添加\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;
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值