急求在JSP中截取字符串的方法(中英文混合处理)?
我想在首页新闻列表中限制字符长度如10个,但是用substring()来做的话,中文和英文长度导致限制的长度就展示不一样了,要顶满格,改如何处理。
急求有没好的JAVA方法提供。。。感谢!
------解决方案--------------------
/*
* Created on 2005-5-13
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package oa.util;
/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class Truncate {
public static String truncate(String source, int len, String delim) {
if (source == null) return null;
int start, stop , byteLen ;
int alen = source.getBytes().length;
//len += len ;
if (len > 0) {
if (alen <= len) return source;
start = stop = byteLen = 0; //TODO effizienter
//stop = (len > alen ? alen : len);
while ( byteLen <= len){
if ( source.substring(stop,stop+1).getBytes().length == 1){
byteLen += 1 ;
}else{
byteLen += 2 ;
}
stop++;
}
StringBuffer sb = new StringBuffer(source.substring(start, stop-1));
if (alen > len) sb.append(delim);
return sb.toString();
}
start = (len < -alen ? 0 : alen + len);
stop = alen;
StringBuffer sb = new StringBuffer(source.substring(start/2, stop/2));
if (-alen <= len) sb.insert(0, delim);
return sb.toString();
}
}