收集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 "...";
}
}
……
【阅读全文】
带...的字符串截取,保证所有字符长度(中文算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 "...";
}
}
……
【阅读全文】
相关文章推荐
- Java精确截取字符串
- Java精确截取字符串,取得字符串前面指定长度字符函数
- Java精确截取字符串/获取字符串前指定长度字符函数
- 精确截取字符串(转载)
- java中常用的字符串的截取方法
- java截取字符串,截串,substring和split,分割字母和数字,正则缝隙
- JAVA 正则表达式截取字符串小例子
- java截取或拆分字符串
- java java中subString、split、stringTokenizer三种截取字符串方法的性能比较
- java 字符串截取的几种方式
- 提供一个JAVA过滤HTML代码和截取字符串的类(包括测试用例)
- java截取包含汉字字符串
- Java字符串的截取
- java截取字符串
- java中截取字符串的方式
- 按字节截取字符串-Java
- java 截取点后面的字符串
- java截取带html标签的字符串,再把标签补全
- Java字符串函数收集
- Android(Java)字符、字符串的查询、检索、截取、合并等操作