Kotlin字符串操作



我正在尝试创建一个逻辑,以便

if I Input "1-2+4" in Android TextView and after clicking a button
the output should Display as follows
1 - 2 = -1 // 1st line
-1 + 4 = 3 // 2nd line and so on...

without BODMAS Rule like, 
first addition then minus etc., it should follow my input sequence

我试了很多字符串函数,但找不到确切的逻辑。。。通过使用字符串函数,我得到了类型不匹配等,诸如此类的错误。。。。我请求任何人抱着我并引导我。。谢谢

这是对您正在寻找的内容的快速迭代。Regex功能强大但很危险,当它们被修改超过原来的用法时,事情就会开始分崩离析。

这里的要点。

  1. 我们在operateBy方法中使用整数进行所有操作,这有助于Kotlin知道我们只使用整数,否则很难知道我们期望的类型,因为Int::minus存在许多不同的类型
  2. 关键的魔力在于Integer.parseInt方法,它获取我们的字符串并使其成为数字,所以我们实际上可以对它们进行数学运算,否则从字符串转换为Int可能会导致意外的结果
  3. 我们使用cmd?.destructured?.run的可空性来暗示我们有一个成功且完全的匹配。否则我们会意识到我们已经到达了输入的末尾

val input = "1-2+4+8-4/7*3"
val regex = Regex("""(-?d+)([-+/*])(-?d+)(.*)""")
parseInput(input)
println("Done!")
fun Int.operateBy(symbol: String, other: Int): Int = when(symbol) {
"-" -> minus(other)
"+" -> plus(other)
"/" -> div(other)
"*" -> times(other)
else -> other
}
fun parseInput(commands: String) {
if (commands.isEmpty()) return
val cmd = regex.find(commands)

cmd?.destructured?.run {
val first = component1()
val second = component2()
val third = component3()
val fourth = component4()
try {
val a = Integer.parseInt(first)
val b = Integer.parseInt(third)
val result = a.operateBy(second, b)
println("$a $second $b = $result")
parseInput("$result$fourth")
} catch (e: NumberFormatException) {
println("Error messaging")
}
}
}

这会打印输出:

1 - 2 = -1
-1 + 4 = 3
3 + 8 = 11
11 - 4 = 7
7 / 7 = 1
1 * 3 = 3
Done!