【问题标题】:Java find whether the string characters are in given rangeJava查找字符串字符是否在给定范围内
【发布时间】:2013-02-11 11:03:10
【问题描述】:

我是 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;
   } 
}

请告诉我这段代码是否正确,或者我在编码方面遗漏了什么。

【问题讨论】:

  • 编译是否正确?我怀疑!

标签: java string unicode encoding utf-8


【解决方案1】:

我建议使用正则表达式,就是这个想法

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

【讨论】:

    【解决方案2】:

    先做一个小修正:

      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 的答案是最好的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 2014-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多