Я перенес код Kotlin @ Lakedaemon на Java.
// auxiliary function
static public String getCharacter(String string, int position) {
char[] characters = string.toCharArray();
return String.valueOf(characters[position]);
}
static public String toPinyin(String asciiPinyin) {
Map<String, String> pinyinToneMarks = new HashMap<String, String>();
pinyinToneMarks.put("a", "āáǎà"); pinyinToneMarks.put("e", "ēéěè");
pinyinToneMarks.put("i", "īíǐì"); pinyinToneMarks.put("o", "ōóǒò");
pinyinToneMarks.put("u", "ūúǔù"); pinyinToneMarks.put("ü", "ǖǘǚǜ");
pinyinToneMarks.put("A", "ĀÁǍÀ"); pinyinToneMarks.put("E", "ĒÉĚÈ");
pinyinToneMarks.put("I", "ĪÍǏÌ"); pinyinToneMarks.put("O", "ŌÓǑÒ");
pinyinToneMarks.put("U", "ŪÚǓÙ"); pinyinToneMarks.put("Ü", "ǕǗǙǛ");
Pattern pattern = Pattern.compile("([aeiouüvÜ]{1,3})(n?g?r?)([012345])");
Matcher matcher = pattern.matcher(asciiPinyin);
StringBuilder s = new StringBuilder();
int start = 0;
while (matcher.find(start)) {
s.append(asciiPinyin, start, matcher.start(1));
int tone = Integer.parseInt(matcher.group(3)) % 5;
String r = matcher.group(1).replace("v", "ü").replace("V", "Ü");
// for multple vowels, use first one if it is a/e/o, otherwise use second one
int pos = r.length() > 1 && "aeoAEO".contains(getCharacter(r,0).toString())? 1 : 0;
if (tone != 0) {
s.append(r, 0, pos).append(getCharacter(pinyinToneMarks.get(getCharacter(r, pos)),tone - 1)).append(r, pos + 1, r.length());
} else {
s.append(r);
}
s.append(matcher.group(2));
start = matcher.end(3);
}
if (start != asciiPinyin.length()) {
s.append(asciiPinyin, start, asciiPinyin.length());
}
return s.toString();
}