易网时代-编程资源站
Welcome
微信登录
编程资源
图片资源库
蚂蚁家优选
PDF转换器
软件资源
软件开发
、
小程序制作
、
系统集成与运维
、
空间租用
、
硬件开发
、
视频监控
、
技术咨询与支持
——联系电话:0311-88999002/88999003
首页
/
操作系统
/
Linux
/
Java中英文字符长度截取问题
/**
* 字符串按字节截取
* @param str 原字符
* @param len 截取长度
* @return String
* @author ivan
* @since 2010.07.05
*/
public
static
String splitString(String str,
int
len) {
return
splitString(str, len,
"..."
);
}
/**
* 字符串按字节截取
* @param str 原字符
* @param len 截取长度
* @param elide 省略符
* @return String
* @author ivan
* @since 2010.07.05
*/
public
static
String splitString(String str,
int
len,String elide) {
if
(str ==
null
) {
return
""
;
}
byte
[] strByte = str.getBytes();
int
strLen = strByte.length;
//int elideLen = (elide.trim().length() == 0) ? 0 : elide.getBytes().length;
int
elideLen =
0
;
if
(len >= strLen || len <
1
) {
return
str;
}
if
(len - elideLen >
0
) {
len = len - elideLen;
}
int
count =
0
;
for
(
int
i =
0
; i < len; i++) {
int
value = (
int
) strByte[i];
if
(value <
0
) {
count++;
}
}
if
(count %
2
!=
0
) {
len = (len ==
1
) ? len +
1
: len -
1
;
}
return
new
String(strByte,
0
, len) + elide.trim();
}
public
static
String subStr(String str,
int
num) {
int
max = num;
try
{
max = trimGBK(str.getBytes(
"GBK"
),num);
}
catch
(UnsupportedEncodingException e) {
e.printStackTrace();
}
int
sum =
0
;
if
(str !=
null
&& str.length() > max) {
StringBuilder sb =
new
StringBuilder(max);
for
(
int
i =
0
; i < str.length(); i++) {
int
c = str.charAt(i);
// if ((c & 0xff00) != 0)
// sum += 2;
// else
sum +=
1
;
if
(sum <= max)
sb.append((
char
) c);
else
break
;
}
return
sb.append(
"..."
).toString();
}
else
return
str !=
null
? str :
""
;
}
public
static
int
trimGBK(
byte
[] buf,
int
n){
int
num =
0
;
boolean
bChineseFirstHalf =
false
;
if
(buf.length < n )
return
buf.length;
for
(
int
i=
0
;i<n;i++)
{
if
(buf[i]<
0
&& !bChineseFirstHalf){
bChineseFirstHalf =
true
;
}
else
{
num++;
bChineseFirstHalf =
false
;
}
}
return
num;
}
收藏该网址
版权所有©石家庄振强科技有限公司2024
冀ICP备08103738号-5
网站地图