首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

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

2012-12-27 
截取字符串其中有汉字问题处理/** * @author zhangyang * @version 1.0 */public class TestStr{public st

截取字符串其中有汉字问题处理
/**
* @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);
    }
}

热点排行