按照字节截取字符串,汉字部分超出不加进来,
输入:“我AND”和 4。返回的是“我AN”
输入:“我AND你”和6 返回的是"我AND",而不是“我AND你”
输入:“我AND”和 4。返回的是“我AN”
输入:“我AND你”和6 返回的是"我AND",而不是“我AND你”
/***
* 按字节长度截取字符串
*@param str 将要截取的字符串参数
*@param toCount截取的字节长度
*@param more 字符串末尾补上的字符串
*@return 返回截取后的字符串
*/
public String substring(String str, int toCount, String more) {
int reInt = 0;
String reStr = "";
if (str == null)
return "";
char[] tempChar = str.toCharArray();
for (int kk = 0; (kk < tempChar.length && toCount > reInt); kk++) {
String s1 = str.valueOf(tempChar[kk]);
byte[] b = s1.getBytes();
reInt += b.length;
if(reInt<=toCount){
reStr += tempChar[kk];
}else{
break;
}
}
if (toCount == reInt || (toCount == reInt - 1))
reStr += more;
return reStr;
}
public static void main(String args[]){
TestFsAction a = new TestFsAction();
//输出 我AN你
System.out.println(a.substring("我AND", 4, "你"));
//输出 我AND一起
System.out.println(a.substring("我AND你", 6, "一起"));
}