Java 按照字节来截取字符串的代码(不会出现半个汉字)
本文导语: 代码如下:/* * Copyright 2012-2013 The Haohui Network Corporation */package com.haohui.common.utils; /** * * 字符串辅助工具 * * * @project baidamei * @author cevencheng * @create 2012-11-30 下午2:42:56 */public class StringTool { /** *截取指定字节长度...
/*
* Copyright 2012-2013 The Haohui Network Corporation
*/
package com.haohui.common.utils;
/**
*
* 字符串辅助工具
*
*
* @project baidamei
* @author cevencheng
* @create 2012-11-30 下午2:42:56
*/
public class StringTool {
/**
*截取指定字节长度的字符串,不能返回半个汉字
* 例如:
* 如果网页最多能显示17个汉字,那么 length 则为 34
* StringTool.getSubString(str, 34);
*
* @param str
* @param length
* @return
*/
public static String getSubString(String str, int length) {
int count = 0;
int offset = 0;
char[] c = str.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] > 256) {
offset = 2;
count += 2;
} else {
offset = 1;
count++;
}
if (count == length) {
return str.substring(0, i + 1);
}
if ((count == length + 1 && offset == 2)) {
return str.substring(0, i);
}
}
return "";
}
}