0

How to solve an example in a string? Let's say we have val example : String = "3+5"

So how do I solve this example? Or if val example : String = "3*5/3"

Latte
  • 5
  • 2
  • There's no built-in way to do this in the Kotlin standard library. You need to either parse the text yourself, or find an arithmetic library you can use. – Tenfour04 Oct 17 '22 at 19:59
  • @Tenfour04 I'm not quite versed in using third party libraries. could you help me? I know how it works in python. And I don’t know how it works in Kotlin. I write in android studio. – Latte Oct 17 '22 at 20:04
  • https://stackoverflow.com/questions/16588064/how-do-i-add-a-library-project-to-android-studio When you find a library you want to use, usually on Github, they usually show you what line to put for `implementation` in the readme. – Tenfour04 Oct 17 '22 at 20:16
  • I like `implementation "net.objhunter:exp4j:0.4.8"`, documentation here: https://www.objecthunter.net/exp4j/ The documentation is in Java, but pretty easy to convert to Kotlin. – Tenfour04 Oct 17 '22 at 20:28

1 Answers1

1

Two ways to achieve it:

  1. Keval - 3rd party dependency

    You can either use Keval.eval("(3+4)(2/8 * 5) % PI") or as an extension function on String, "(3+4)(2/8 * 5) % PI".keval(). This will return the calculated value as Double. For your example, "3*5/3".keval().

    To use it, add implementation("com.notkamui.libs:keval:0.8.0") in dependencies in app level build.gradle file and sync gradle. Then, use it in any file as mentioned in the above para, put the cursor on the line and press Alt + Enter (or hover for suggestions) to import the necessary imports.

    Look into its Readme.md on the provided link for more usage and implementation details.

  2. Custom String parsing using BODMAS rule

    You can split the string using the BODMAS rule, parse the split array as int/double, if it throws exception, it means the substring is an expression too, again split it using BODMAS, parse and perform the calculation.

Lalit Fauzdar
  • 5,953
  • 2
  • 26
  • 50