首页 > 解决方案 > Kotlin中字符串之间的异或操作

问题描述

我是 Kotlin 的新手,我想在字符串之间执行 XOR 操作。

我知道我可以通过将字符串转换为 char 数组并对每个字符执行 XOR来执行 Java

但是 Kotlin 中是否有任何可用的功能可以让我轻松做到这一点。

就像我有三个字符串 Y1、Y2 和 Y3

我想在它们之间执行 XOR 操作,比如

 var result = Y1 XOR Y2 XOR Y3

我不知道如何使用 Kotlin 实现,任何人都可以帮助我,在此先感谢

标签: androidkotlin

解决方案


编写一个infix fun来实现该 Java 函数。

infix fun String.xor(that: String) = mapIndexed { index, c ->
    that[index].toInt().xor(c.toInt())
}.joinToString(separator = "") {
    it.toChar().toString()
}

"102" xor "103" xor "104" // "105"

推荐阅读