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"
CodePudding user response:
Two ways to achieve it:
-
You can either use
Keval.eval("(3 4)(2/8 * 5) % PI")
or as an extension function onString
,"(3 4)(2/8 * 5) % PI".keval()
. This will return the calculated value asDouble
. For your example,"3*5/3".keval()
.To use it, add
implementation("com.notkamui.libs:keval:0.8.0")
in dependencies in app levelbuild.gradle
file and sync gradle. Then, use it in any file as mentioned in the above para, put the cursor on the line and pressAlt 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.
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.