今天一个朋友问我如何截取文章内容中的指定长度内容,多余了就加省略号,于是随手写了方法,顺便拿出给需要的人参考下:
1
/** *//**
2
* 截取字符串的前targetCount个字符
3
* @param str 被处理字符串
4
* @param targetCount 截取长度
5
* @param more 后缀字符串
6
* @version 0.1
7
* @author aithero
8
* @return String
9
*/
10
public static String subContentString(String str, int targetCount,String more)
11
{
12
int initVariable = 0;
13
String restr = "";
14
if (str == null)
{
15
return "";
16
}else if(str.length()<=targetCount)
{
17
return str;
18
}else
{
19
char[] tempchar = str.toCharArray();
20
for (int i = 0; (i < tempchar.length && targetCount > initVariable); i++)
{
21
String s1 = str.valueOf(tempchar[i]);
22
byte[] b = s1.getBytes();
23
initVariable += b.length;
24
restr += tempchar[i];
25
}
26
}
27
if (targetCount == initVariable || (targetCount == initVariable - 1))
{
28
restr += more;
29
}
30
return restr;
31
}
32
33
/** *//**
* 截取指定文章内容
35
* @param str
36
* @param n
37
* @author aithero
38
* @return String
39
*/
40
public static String subContent(String str,int n)
41
{
42
//格式化字符串长度,超出部分显示省略号,区分汉字跟字母。汉字2个字节,字母数字一个字节
43
String temp= "";
44
if(str.length()<n)
{//如果长度比需要的长度n小,返回原字符串
45
return str;
46
}else
{
47
int t=0;
48
char[] tempChar=str.toCharArray();
49
for(int i=0;i<tempChar.length&&t<n;i++)
50
{
51
if((int)tempChar[i]>=0x4E00 && (int)tempChar[i]<=0x9FA5)//是否汉字
52
{
53
temp+=tempChar[i];
54
t+=2;
55
}
56
else
57
{
58
temp+=tempChar[i];
59
t++;
60
}
61
}
62
return (temp+"
");
63
}
64
}
65