您的位置:首页 > 编程语言 > Java开发

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

2016-02-01 13:52 549 查看
这感觉其实是一个不太正规的方法,只是我在写爬取网页的东西的时候突然想到这可以用来判断是否包含中文,就是利用编码转码的方法:

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));
}
}
}


最后得到结果:



但这里有一个必须注意的地方,因为部分字符经编码后也会变成%数字这种格式,所以还必须判断该数字代表的是字符还是中文的组成码,具体可根据URL编码表http://www.w3school.com.cn/tags/html_ref_urlencode.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: