问题描述
假设有一个由两个字符组成的 String
,它应该代表 ISO 639 国家或语言名称.
Suppose to have a two-characters String
, which should represent the ISO 639 country or language name.
你知道,区域设置
类有两个函数 getISOLanguages
和 getISOCountries
,分别返回包含所有 ISO 语言和 ISO 国家/地区的 String
数组.
要检查特定的 String
对象是否是有效的 ISO 语言或 ISO 国家/地区,我应该在该数组中查找匹配的 String
.好的,我可以通过使用二进制搜索来做到这一点(例如 Arrays.binarySearch
或 ApacheCommons ArrayUtils.contains
).
To check if a specific String
object is a valid ISO language or ISO country I should look inside that arrays for a matching String
. Ok, I can do that by using a binary search (e.g. Arrays.binarySearch
or the ApacheCommons ArrayUtils.contains
).
问题是:存在任何实用程序(例如来自 Guava 或 Apache Commons 库)提供更简洁的方法,例如一个返回 boolean
以验证 String
为有效 ISO 639 语言或 ISO 639 国家/地区的函数?
The question is: exists any utility (e.g. from Guava or Apache Commons libraries) that provides a cleaner way, e.g. a function that returns a boolean
to validate a String
as a valid ISO 639 language or ISO 639 Country?
例如:
public static boolean isValidISOLanguage(String s)
public static boolean isValidISOCountry(String s)
推荐答案
我不会费心使用二进制搜索或任何第三方库 - HashSet
很适合这个:
I wouldn't bother using either a binary search or any third party libraries - HashSet
is fine for this:
public final class IsoUtil {
private static final Set<String> ISO_LANGUAGES = Set.of(Locale.getISOLanguages());
private static final Set<String> ISO_COUNTRIES = Set.of(Locale.getISOCountries());
private IsoUtil() {}
public static boolean isValidISOLanguage(String s) {
return ISO_LANGUAGES.contains(s);
}
public static boolean isValidISOCountry(String s) {
return ISO_COUNTRIES.contains(s);
}
}
您可以先检查字符串长度,但我不确定我会不会打扰 - 至少不会,除非您想保护自己免受性能攻击,在这种情况下您会收到大量字符串需要很长时间才能散列.
You could check for the string length first, but I'm not sure I'd bother - at least not unless you want to protect yourself against performance attacks where you're given enormous strings which would take a long time to hash.
如果您确实想使用第三方库,ICU4J 是最有可能的竞争者 - 但它的列表很可能比 Locale
支持的列表更新,因此您可能希望在任何地方都使用 ICU4J.
If you do want to use a 3rd party library, ICU4J is the most likely contender - but that may well have a more up-to-date list than the ones supported by Locale
, so you would want to move to use ICU4J everywhere, probably.
这篇关于在 Java 中检查字符串是否为 ISO 语言的 ISO 国家的更简洁方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!