您的位置:首页 > 编程语言 > Java开发

收集java精确截取字符串

2007-07-10 19:35 239 查看
====================================

带...的字符串截取,保证所有字符长度(中文算2)不超过max:

例:

left("abcdefg", 7)="abcdefg"

left("abcdefg", 6)="abc..."

left("中文abcdefg", 9)="中文ab..."

package com.crackj2ee.util;

/**

* @author Xuefeng, asklxf@163.com

*/

public class StringUtil {

public static String left(String s, int max) {

char[] cs = s.toCharArray();

int count = 0;

int last = cs.length;

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

if(cs[ i ]>255)

count+=2;

else

count++;

if(count>max) {

last = i+1;

break;

}

}

if(count<=max) // string is short or just the size!

return s;

// string is too long:

max -= 3;

for(int i=last-1; i>=0; i--) {

if(cs[ i ]>255)

count-=2;

else

count--;

if(count<=max) {

return s.substring(0, i) + "...";

}

}

return "...";

}

}
……
【阅读全文】
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: