Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to split string on operator(s) (/*+-)

I am making an android calculator and trying to get it to split the string when it encounters an operator (for example "*"). However, val one returns the entire string 20×20 instead of 20.

fun main() {
    var equation = "20*20"
    val splitValue = equation.split("[/*-+]")
    var one = splitValue[0]
    println(one)
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Unlike split in Java, split in Kotlin does not treat the string that you pass to it as a regular expression. split in Kotlin takes one of these things:

  • a Regex object
  • a list of String delimiters, passed as varargs
  • a list of Char delimiters, passed as varargs

So you can either do:

equation.split("[/*\\-+]".toRegex()) // toRegex creates a Regex object

(Note that it is important that you escape the - in the regex. Otherwise, itt means "from…to" (*-+ means all the characters from * to +), and the string will be split on more characters than you would expect.)

or

equation.split('/', '*', '+', '-')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading