gpt4 book ai didi

java - Java 中的音译。重新定义字符串中的每个字符

转载 作者:行者123 更新时间:2023-12-02 04:17:31 24 4
gpt4 key购买 nike

方法的目的是字符串的音译,例如:афиваў => afivaw。问题是:我无法使用 charAt 方法重新定义,因为有一些字母需要音译为两个符号 'ш' => "sh"。我试试这个:

public static String belrusToEngTranlit (String text){
char[] abcCyr = {'a','б','в','г','д','ё','ж','з','и','к','л','м','н','п','р','с','т','у','ў','ф','х','ц','ш','щ','ы','э','ю','я'};
String[] abcLat = {"a","b","v","g","d","jo","zh","z","i","k","l","m","n","p","r","s","t","u","w","f","h","ts","sh","sch","","e","ju","ja"};
for (int i = 0; i < text.length(); i++) {
for(int x = 0; x < abcCyr.length; x++ )
if (text.charAt(i) == abcCyr[x]) {
text.charAt(i) = abcLat[x];
}
}
return text;
}

也许你可以推荐我一些除了 charAt 之外的东西?

最佳答案

字符串是不可变的,因此您无法更改其中的任何文本。所以你可以使用StringBuilder来存储结果。请参阅下面的代码。

public static String belrusToEngTranlit (String text){
char[] abcCyr = {'a','б','в','г','д','ё','ж','з','и','к','л','м','н','п','р','с','т','у','ў','ф','х','ц','ш','щ','ы','э','ю','я'};
String[] abcLat = {"a","b","v","g","d","jo","zh","z","i","k","l","m","n","p","r","s","t","u","w","f","h","ts","sh","sch","","e","ju","ja"};

StringBuilder builder = new StringBuilder();

for (int i = 0; i < text.length(); i++) {
for(int x = 0; x < abcCyr.length; x++ )
if (text.charAt(i) == abcCyr[x]) {
builder.append(abcLat[x]);
}
}
return builder.toString();
}

关于java - Java 中的音译。重新定义字符串中的每个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21509751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com