Created
September 20, 2017 17:49
-
-
Save menion/8376d7a244f8a88cdee3fa1532ee4115 to your computer and use it in GitHub Desktop.
Extraction of language from MapsForge based file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Extracts substring of preferred language from multilingual string.<br/> | |
* Example multilingual string: "Base\ren\bEnglish\rjp\bJapan\rzh_py\bPin-yin". | |
* <p/> | |
* Use '\r' delimiter among names and '\b' delimiter between each language and name. | |
*/ | |
private String extract(String s) { | |
// check string | |
if (s == null || s.trim().isEmpty()) { | |
return null; | |
} | |
// prepare data | |
String lang = mPreferredLanguage; | |
String[] langNames = s.split("\r"); | |
// handle preferred language | |
if (lang == null) { | |
String[] langName = langNames[0].split("\b"); | |
if (langName.length == 1) { | |
return langName[0]; | |
} | |
// set english as default | |
lang = "en"; | |
} | |
// check possible languages | |
String fallback = null; | |
for (int i = 1; i < langNames.length; i++) { | |
String[] langName = langNames[i].split("\b"); | |
if (langName.length != 2) { | |
continue; | |
} | |
// Perfect match | |
if (langName[0].equalsIgnoreCase(lang)) { | |
return langName[1]; | |
} | |
// Fall back to base, e.g. zh-min-lan -> zh | |
if (fallback == null && | |
!langName[0].contains("-") && | |
(lang.contains("-") || lang.contains("_")) && | |
lang.toLowerCase(Locale.ENGLISH).startsWith(langName[0].toLowerCase(Locale.ENGLISH))) { | |
fallback = langName[1]; | |
} | |
} | |
// return best default value | |
if (fallback != null && fallback.length() > 0) { | |
return fallback; | |
} | |
String[] langName = langNames[0].split("\b"); | |
if (langName.length == 2) { | |
return langName[1]; | |
} else { | |
return langNames[0]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment