2013-02-11 155 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的回答是最好的,在长度/可读性方面。