java 字符串截子

import java.io.IOException;

 

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.tagext.TagSupport;

 

public class CutStringTag extends TagSupport{

 

/**

*/

private static final long serialVersionUID = 1L;

protected String value;

protected int length;

protected boolean addPoint;

public int doEndTag() throws JspException {

try {

pageContext.getOut().write(getLimitLengthString(value,length,addPoint));

} catch (IOException e) {

e.printStackTrace();

}

return SKIP_BODY;

}

 

private String subStr(String str, int max,boolean isAddpoint){

int sum = 0;

if(str!=null){

StringBuilder sb = new StringBuilder(max);

for (int i = 0; i < str.length(); i++) {

int c = str.charAt(i);

if((c & 0xff00) != 0)

sum+=2;

else

sum+=1;

if(sum<=max)

sb.append((char)c);

else

break;

}

if(isAddpoint){

return sb.append("...").toString();

}else{

return sb.toString();

}

}else

return str!=null ? str : "";

}

public String getLimitLengthString(String str, int len,boolean isAddpoint) {

String result ="";

try {

int counterOfDoubleByte = 0;

byte[] b = str.getBytes("gb2312");

if (b.length <= len){

if(isAddpoint){

return str+"...";

}else{

return str;

}

}

for (int i = 0; i < len; i++) {

if (b[i] < 0)

counterOfDoubleByte++;

}

if (counterOfDoubleByte % 2 == 0)

result= new String(b, 0, len, "gb2312");

else

result= new String(b, 0, len - 1, "gb2312");

if(isAddpoint){

result=result + "...";

}

return result;

} catch (Exception ex) {

ex.printStackTrace();

return result;

}

}

public void setLength(int length) {

this.length = length;

}

 

public void setValue(String value) {

this.value = value;

}

 

public void setAddPoint(boolean addPoint) {

this.addPoint = addPoint;

}

 

 

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值