用字符串中的多个字符替换多个字符

时间:2021-07-21 08:42:05

标签: kotlin replace replaceall

我正在寻找在 Kotlin 中用相应的不同字符替换多个不同字符的可能性。

举个例子,我在 PHP 中寻找一个类似的函数:

var newWord = word.replace("ā", "a")
newWord = word.replace("ē", "e")
newWord = word.replace("ī", "i")
newWord = word.replace("ō", "o")
newWord = word.replace("ū", "u")

现在在 Kotlin 中,我只是像这样调用 5 次相同的函数(对于每个人声):

MultiBlocProvider

这当然可能不是最好的选择,如果我必须用一个单词列表而不是一个单词来做到这一点。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:4)

您可以通过遍历 word 中的每个字符来维护字符映射并替换所需的字符。

val map = mapOf('ā' to 'a', 'ē' to 'e' ......)
val newword = word.map { map.getOrDefault(it, it) }.joinToString("")

如果你想做多个单词,可以创建一个扩展函数,以提高可读性

fun String.replaceChars(replacement: Map<Char, Char>) =
   map { replacement.getOrDefault(it, it) }.joinToString("")


val map = mapOf('ā' to 'a', 'ē' to 'e', .....)
val newword = word.replaceChars(map)

答案 1 :(得分:3)

使用 ziptransform 函数添加另一种方法

val l1 = listOf("ā", "ē", "ī", "ō", "ū")
val l2 = listOf("a", "e", "i", "o", "u")

l1.zip(l2) { a, b ->  word = word.replace(a, b) }

l1.zip(l2) 将构建 List<Pair<String,String>>,即:

[(ā, a), (ē, e), (ī, i), (ō, o), (ū, u)]

transform 函数 { a, b -> word = word.replace(a, b) } 将允许您访问每个列表 (l1 ->a , l2->b) 中的每个项目。