/*
 * Created on 2005-5-13
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package org.chapter2;

/**
 * @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 void main(String[] args) {
		String str = "如ab何对较长的字符串省略显示";
		String strChar = "abcdefghi";
		System.out.println(Truncate.truncate(str,8,"..."));
	}
	
	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();
	}
}
