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

Advertisements

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 :

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('/', '*', '+', '-')

Leave a ReplyCancel reply