Java code of of which intercepts strings in bytes does not show half a Chinese character
- 2020-04-01 02:47:45
- OfStack
package com.haohui.common.utils;
/**
* <pre>
* String helper
* </pre>
*
* @project baidamei
* @author cevencheng <cevencheng@gmail.com>
* @create 2012-11-30 In the afternoon 2:42:56
*/
public class StringTool {
/**
*<b> Intercepts a string of specified bytes. Cannot return half a Chinese character </b>
* Such as:
* If the web page can be displayed at most 17 Two Chinese characters, then length For the 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 "";
}
}