截取指定长度的字符串

王朝other·作者佚名  2008-05-31
窄屏简体版  字體: |||超大  

/**

* 截取指定长度的字符串,中文算2个长度,若过长,返回xxx...,否则返回原串

* @param s Original String.

* @param max Max length.

* @return Left part of string.

*/

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 "...";

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航