紫金城之巅
涤尽生活繁华,牧放自由心境
BlogJava
首页
新随笔
联系
聚合
管理
posts - 0, comments - 1, trackbacks - 0
Java文单缩略内容截取
今天一个朋友问我如何截取文章内容中的指定长度内容,多余了就加省略号,于是随手写了方法,顺便拿出给需要的人参考下:
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
/** */
/**
34
* 截取指定文章内容
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
posted on 2006-12-11 11:48
胧夜
阅读(311)
评论(1)
编辑
收藏
所属分类:
聚剑阁
FeedBack:
#
re: Java文单缩略内容截取
2007-07-04 15:48 |
Strong Yuan
没有考虑到html
回复
更多评论
新用户注册
刷新评论列表
只有注册用户
登录
后才能发表评论。
网站导航:
博客园
IT新闻
Chat2DB
C++博客
博问
管理
相关文章:
WEB2.0站中的layout个性化定制探讨(想说web开发系列之一)
Java文单缩略内容截取
<
2007年7月
>
日
一
二
三
四
五
六
24
25
26
27
28
29
30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
1
2
3
4
留言簿
给我留言
查看公开留言
查看私人留言
文章分类
聚剑阁(2)
文章档案
2007年12月 (1)
2006年12月 (1)
搜索
最新评论
1. re: Java文单缩略内容截取
没有考虑到html
--Strong Yuan