我的问题是,我想检查我的字符串匹配ASCII字符集。匹配如果字符串只包含ASCII字符集
我试图在我的android项目中使用Guava库。问题是,这个库有太多的权重(安装的应用程序大小为41 MB,并且番石榴库变为45MB)。
从番石榴库我只需要这样:
CharMatcher.ascii().matchesAllOf();
你有我应该如何正确地检查我的字符串任何想法,或有任何其他轻质库?
谢谢!
我的问题是,我想检查我的字符串匹配ASCII字符集。匹配如果字符串只包含ASCII字符集
我试图在我的android项目中使用Guava库。问题是,这个库有太多的权重(安装的应用程序大小为41 MB,并且番石榴库变为45MB)。
从番石榴库我只需要这样:
CharMatcher.ascii().matchesAllOf();
你有我应该如何正确地检查我的字符串任何想法,或有任何其他轻质库?
谢谢!
的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
优秀!感谢您的回答! – researcher
你可以试试这个:
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?
从RealHowTo的answer到In 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 */ } }
看番石榴源和复制方法和其他调用栈到本地。 https://github.com/google/guava/blob/master/guava/src/com/google/common/base/CharMatcher.java – kosa
@Nambari根据你的答案我不会有任何许可问题? – Ololoking
@Diyarbakir请在标记之前阅读此问题。 – Seth