2013-02-11 154 views
1

我是新來的java和編碼,因此這個問題。Java查找字符串是否在給定範圍內

我基本上有一個文本文件,其中包含以十六進制值表示的一組有效字符。 例如: 0x2000-0x4002,0x5002-0x5F00

現在我有另一個文件包含字符串。例如: 我正在嘗試使用此文件。

我的問題是檢查第二個文件的每個字符是否有效,並在上述文件描述的範圍內。

所以這是我在做什麼:

public class Test 
{ 
    //This is a function used to build the ranges. 
    public void build range() {} 

    //This function will test whether the string str is in given range. 
    public bool check range(String str) 
    { 
     int codePointCount = str.codePointCount(0, str.length()); 
     for(in ti =0; i< codePointCount; i++) 
     { 
      int value = str.codePointAt(i); 
      if(value >= 2000 && value <= 4002) 
      continue; 
      if(value >= 5002 && value <= 5F00) 
      continue; 
      return false; 
     } 
     return true; 
    } 
} 

請讓我知道這個代碼是正確的還是我缺少相對於編碼的東西。

+1

它甚至編譯正確嗎?我懷疑! – Abubakkar 2013-02-11 11:06:53

回答

2

我建議使用正則表達式,這是觀念

boolean ok = !str.matches(".*[^\u2000-\u4002\u5002-\u5F00].*"); 
0

首先小幅盤整:

for (int i = 0; i < str.length();) 
    { 
     int value = str.codePointAt(i); 
     i += Character.charCount(value); 
     if(value >= 0x2000 && value <= 0x4002) 
     continue; 
     if(value >= 0x5002 && value <= 0x5F00) 
     continue; 
     return false; 
    } 

但@EvgeniyDororfeev的回答是最好的,在長度/可讀性方面。