Sar*_*ker 5 replace replaceall kotlin
我正在寻找在 Kotlin 中用相应的不同字符替换多个不同字符的可能性。
\n作为一个例子,我在 PHP 中寻找与此类似的函数:
\nstr_replace(["\xc4\x81", "\xc4\x93", "\xc4\xab", "\xc5\x8d", "\xc5\xab"], ["a","e","i","o","u"], word)\nRun Code Online (Sandbox Code Playgroud)\n现在在 Kotlin 中,我只需调用 5 次相同的函数(对于每个声音),如下所示:
\nvar newWord = word.replace("\xc4\x81", "a")\nnewWord = word.replace("\xc4\x93", "e")\nnewWord = word.replace("\xc4\xab", "i")\nnewWord = word.replace("\xc5\x8d", "o")\nnewWord = word.replace("\xc5\xab", "u")\nRun Code Online (Sandbox Code Playgroud)\n如果我必须使用一系列单词而不仅仅是一个单词来执行此操作,那么这当然可能不是最好的选择。有没有办法做到这一点?
\n您可以通过迭代 .txt 文件中的每个字符来维护字符映射并替换所需的字符word。
val map = mapOf('\xc4\x81' to 'a', '\xc4\x93' to 'e' ......)\nval newword = word.map { map.getOrDefault(it, it) }.joinToString("")\nRun Code Online (Sandbox Code Playgroud)\n如果您想对多个单词执行此操作,可以创建扩展函数以提高可读性
\nfun String.replaceChars(replacement: Map<Char, Char>) =\n map { replacement.getOrDefault(it, it) }.joinToString("")\n\n\nval map = mapOf('\xc4\x81' to 'a', '\xc4\x93' to 'e', .....)\nval newword = word.replaceChars(map)\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
1376 次 |
| 最近记录: |