天天看點

截取字元串(判斷漢字)

Code:

/**

* 截取字元串 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 "";