2016-03-02 167 views
1

我的问题是,我想检查我的字符串匹配ASCII字符集。匹配如果字符串只包含ASCII字符集

我试图在我的android项目中使用Guava库。问题是,这个库有太多的权重(安装的应用程序大小为41 MB,并且番石榴库变为45MB)。

番石榴库我只需要这样:

CharMatcher.ascii().matchesAllOf(); 

你有我应该如何正确地检查我的字符串任何想法,或有任何其他轻质库?

谢谢!

+1

看番石榴源和复制方法和其他调用栈到本地。 https://github.com/google/guava/blob/master/guava/src/com/google/common/base/CharMatcher.java – kosa

+0

@Nambari根据你的答案我不会有任何许可问题? – Ololoking

+0

@Diyarbakir请在标记之前阅读此问题。 – Seth

回答

2

的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

+1

优秀!感谢您的回答! – researcher

-2

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

相关问题