首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Kotlin字符串运算

Kotlin字符串运算
EN

Stack Overflow用户
提问于 2022-09-27 16:53:24
回答 1查看 43关注 0票数 0

我试图创建这样一个逻辑

代码语言:javascript
复制
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

我尝试了很多字符串函数,但找不到确切的logic...By使用字符串函数,我得到了类型错配等,这样的错误.我请求任何人抱着并引导我。谢谢

EN

回答 1

Stack Overflow用户

发布于 2022-09-27 20:23:01

这是你正在寻找的东西的快速迭代。Regex功能强大,但很危险,当它们被修改过最初的用法时,事情就开始崩溃了。

重点在这里。

  1. 我们在operateBy方法中对整数做所有事情,这有助于Kotlin知道我们只处理整数,否则很难知道我们所期望的哪种类型,这是因为Int存在许多不同类型::减去
  2. 关键魔术在Integer.parseInt方法中,它接受我们的字符串并使它们成为数字,所以我们实际上可以对它们进行数学运算,否则从字符串到Int的转换会导致意想不到的结果--
  3. --我们使用cmd?.destructured?.run的空性来表示我们有一个成功的完全匹配。否则,我们会意识到我们已经到达了输入

的末尾。

代码语言:javascript
复制
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")
        }
    }
}

这将打印输出:

代码语言:javascript
复制
1 - 2 = -1
-1 + 4 = 3
3 + 8 = 11
11 - 4 = 7
7 / 7 = 1
1 * 3 = 3
Done!
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73871215

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档