java判断字符串中是否含有中文

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/name_z/article/details/50617960

这感觉其实是一个不太正规的方法,只是我在写爬取网页的东西的时候突然想到这可以用来判断是否包含中文,就是利用编码转码的方法:
url中网址中不能直接包含中文,中文需要先经过编码转换成一串字符(例如”你好”>>”%E4%BD%A0%E5%A5%BD”),而英文经过编码后是不会改变的(”hello”>>”hello”),所以:

public class Test{

    public static boolean isChinese(String str) throws UnsupportedEncodingException
    {
        int len = str.length();
        for(int i = 0;i < len;i ++)
        {
            String temp = URLEncoder.encode(str.charAt(i) + "", "utf-8");
            if(temp.equals(str.charAt(i) + ""))
                continue;
            String[] codes = temp.split("%");
            //判断是中文还是字符(下面判断不精确,部分字符没有包括)
            for(String code:codes)
            {
                if(code.compareTo("40") > 0)
                    return true;
            }
        }
        return false;
    }

    public static void main(String[] args) throws Exception
    {
       while(true)
       {
           Scanner in = new Scanner(System.in);
           String temp = in.nextLine();
           System.out.println(temp + "是否含有中文:" + isChinese(temp));
       }
    }
}

最后得到结果:
result
但这里有一个必须注意的地方,因为部分字符经编码后也会变成%数字这种格式,所以还必须判断该数字代表的是字符还是中文的组成码,具体可根据URL编码表http://www.w3school.com.cn/tags/html_ref_urlencode.html

猜你喜欢

转载自blog.csdn.net/name_z/article/details/50617960