這感覺其實是一個不太正規的方法,只是我在寫爬取網頁的東西的時候突然想到這可以用來判斷是否包含中文,就是利用編碼轉碼的方法:
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