【问题标题】:Replace multiple chars with multiple chars in string用字符串中的多个字符替换多个字符
【发布时间】:2021-07-21 08:42:05
【问题描述】:

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

例如,我在 PHP 中寻找与此类似的函数:

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

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

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

如果我必须使用单词列表而不是一个单词来执行此操作,这当然可能不是最佳选择。有没有办法做到这一点?

【问题讨论】:

    标签: kotlin replace replaceall


    【解决方案1】:

    您可以通过遍历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)
    

    【讨论】:

    • 请注意,对于低于 24 的 API 版本,map.getOrDefault 必须替换为 map[it] ?: it
    【解决方案2】:

    只是使用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&lt;Pair&lt;String,String&gt;&gt;,即:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-15
      • 1970-01-01
      • 2013-03-14
      • 2022-01-08
      • 1970-01-01
      • 2016-09-10
      相关资源
      最近更新 更多