java 截取字符串(判断汉字)
程序员文章站
2024-02-19 20:11:52
复制代码 代码如下:/** * 截取字符串 len为字节长度 * @param str * @param len * @return * @throws unsupport...
复制代码 代码如下:
/**
* 截取字符串 len为字节长度
* @param str
* @param len
* @return
* @throws unsupportedencodingexception
*/
public static string getlimitlengthstring( string str,int len){
try{
int counterofdoublebyte = 0;
byte[] b = str.getbytes("gb2312");
if(b.length <= len)
return str;
for(int i = 0; i < len; i++){
if(b[i] < 0)
counterofdoublebyte++;
}
if(counterofdoublebyte % 2 == 0)
return new string(b, 0, len, "gb2312");
else
return new string(b, 0, len - 1, "gb2312");
}catch(exception ex){
dbtools.error(ex);
return "";
}
}