The code copy is as follows:
/*
* Copyright 2012-2013 The Haohui Network Corporation
*/
package com.haohui.common.utils;
/**
* <pre>
* String helper
* </pre>
*
* @project baidamei
* @author cevencheng <[email protected]>
* @create 2012-11-30 2:42:56 pm
*/
public class StringTool {
/**
*<b>Intercepting a string of specified byte length cannot return half a Chinese character</b>
*For example:
*If the web page can display up to 17 Chinese characters, then the length is 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 "";
}
}