读书人

截取字符串其中有汉字有关问题处理

发布时间: 2012-12-27 10:17:09 作者: rapoo

截取字符串其中有汉字问题处理
/**
* @author zhangyang
* @version 1.0
*/
public class TestStr{
public static void main(String[] args) throws Exception{
String str = "我爱mywife";
System.out.println(cutString(str,5));
}
public static String cutString(String str,int length) throws Exception{
//参数检查--条件限制,各位自己处理
StringBuffer sb=new StringBuffer();
int count=0,i=0;
for(;i<length&&count<length;i++,count++){
sb.append(str.charAt(i));
if(String.valueOf(str.charAt(i)).matches("[^\\x00-\\xff]")){
count++;
}
}
return sb.toString();
}
}





程序做了点精简,最终版如下:
public class Test{
public static void main(String[] args) throws Exception{
String str = "我爱mywife";
System.out.println(cutString(str,5));
}
public static String cutString(String str,int length) throws Exception{
int count=0,i=0;
for(;i<length&&count<length;i++,count++){
if(String.valueOf(str.charAt(i)).matches("[^\\x00-\\xff]")){
count++;
}
}
return new String(str.toCharArray(),0,i);
}
}

读书人网 >编程

热点推荐