【问题标题】:Match if String contains only ASCII character set [duplicate]如果字符串仅包含 ASCII 字符集则匹配 [重复]
【发布时间】:2016-06-15 13:58:08
【问题描述】:

我的问题是我想检查我的 String 是否匹配 ASCII 字符集。

我尝试在我的 android 项目中使用 Guava 库。问题是这个库太重了(安装的应用程序大小是 41 MB,而 Guava 库变成了 45MB)。

来自 Guava 库我只需要这个:

CharMatcher.ascii().matchesAllOf();

你有什么想法我应该如何正确检查我的字符串,或者还有其他轻量级库吗?

谢谢!

【问题讨论】:

标签: java android string ascii guava


【解决方案1】:

RealHowToanswerIn Java, is it possible to check if a String is only ASCII?

你可以用java.nio.charset.Charset来做。

import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

public class StringUtils {

  static CharsetEncoder asciiEncoder = 
      Charset.forName("US-ASCII").newEncoder(); // or "ISO-8859-1" for ISO Latin 1

  public static boolean isPureAscii(String v) {
    return asciiEncoder.canEncode(v);
  }

  public static void main (String args[])
    throws Exception {

     String test = "Réal";
     System.out.println(test + " isPureAscii() : " + StringUtils.isPureAscii(test));
     test = "Real";
     System.out.println(test + " isPureAscii() : " + StringUtils.isPureAscii(test));

     /*
      * output :
      *   Réal isPureAscii() : false
      *   Real isPureAscii() : true
      */
  }
}

Detect non-ASCII character in a String

【讨论】:

    【解决方案2】:

    你可以试试这个:

    private static boolean isAllASCII(String input) {
        boolean isASCII = true;
        for (int i = 0; i < input.length(); i++) {
            int c = input.charAt(i);
            if (c > 0x7F) {
                isASCII = false;
                break;
            }
        }
        return isASCII;
    }
    

    参考In Java, is it possible to check if a String is only ASCII?

    【讨论】:

      【解决方案3】:

      java代码是:

      public static boolean isAsciiPrintable(String str) {
        if (str == null) {
            return false;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if (isAsciiPrintable(str.charAt(i)) == false) {
                return false;
            }
        }
        return true;
        }
          public static boolean isAsciiPrintable(char ch) {
        return ch >= 32 && ch < 127;
        }
      }
      

      参考:http://www.java2s.com/Code/Java/Data-Type/ChecksifthestringcontainsonlyASCIIprintablecharacters.htm

      【讨论】:

      • 太棒了!感谢您的回答!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-19
      • 2022-09-24
      • 2020-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多