java 如何获取语言环境的iso2语言代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5582349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get iso2 language code for locale?
提问by cupakob
I'm getting the iso2 language code this way:
我通过这种方式获取 iso2 语言代码:
public String getLang(Locale language)
return language.toString().substring(0,2).toLowerCase()
}
Is there better way to do this?
有没有更好的方法来做到这一点?
edit: when i use getLanguage, i get an empty string.
编辑:当我使用 getLanguage 时,我得到一个空字符串。
回答by Pa?lo Ebermann
What about
关于什么
public String getLang(Locale language)
return language.getLanguage();
}
Of course, this will only be a iso 639-1 2-lettercode if there is one defined for this language, otherwise it may return a 3-letter code (or even longer).
当然,如果为这种语言定义了一个iso 639-1 2-lettercode,这将只是一个iso 639-1 2-lettercode,否则它可能返回一个3-letter code(甚至更长)。
Your code will give silly results if you have a locale without language code (like _DE
) (mine will then return the empty string, which is a bit better, IMHO). If the locale contains a language code, it will return it, but then you don't need the toLowerCase()
call.
如果您的语言环境没有语言代码(如_DE
),您的代码将给出愚蠢的结果(然后我的将返回空字符串,这更好一点,恕我直言)。如果语言环境包含语言代码,它将返回它,但您不需要toLowerCase()
调用。
回答by Brod
I had the same questions and this is what I found.
我有同样的问题,这就是我发现的。
If you create the Locale
with the constructor as:
如果Locale
使用构造函数创建,则为:
Locale locale = new Locale("en_US");
and then you call getLanguage
:
然后你打电话getLanguage
:
String language = locale.getLanguage();
The value of language
will be "en_us";
的值language
将是“en_us”;
If you create the Locale
with the builder:
如果您Locale
使用构建器创建:
Locale locale = new Locale.Builder().setLanguage("en").setRegion("US").build()
Then the value locale.getLanguage()
will return "en".
然后该值locale.getLanguage()
将返回“en”。
This is strange to me but it's the way it was implemented.
这对我来说很奇怪,但这就是它的实施方式。
So this was the long answer to explain that if you want the language code to return a two-letter ISO language you need to use the Java Locale
builder or do some string manipulation.
所以这是解释如果您希望语言代码返回两个字母的 ISO 语言您需要使用 Java构建器或进行一些字符串操作的长答案。Locale
Your method with substring
works but I would use something like I wrote below to cover instances where the delimiter may be "-" or "_".
你的方法substring
有效,但我会使用我在下面写的东西来覆盖分隔符可能是“-”或“_”的实例。
public String getLang(Locale language)
String[] localeStrings = (language.split("[-_]+"));
return localeStrings[0];
}
回答by saint
What about using the toLanguageTag()
method?
使用toLanguageTag()
方法呢?
Example:
例子:
public String getLang(Locale language) {
return language.toLanguageTag();
}
回答by Riduidel
Maybe by calling Locale#getLanguage()
也许通过调用 Locale#getLanguage()
回答by Thomas
Locale locale = ?; locale.getLanguage();
Locale locale = ?; locale.getLanguage();