Home > Net >  How to split string on operator(s) (/* -)
How to split string on operator(s) (/* -)

Time:01-29

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 20x20 instead of 20.

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

CodePudding user response:

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('/', '*', ' ', '-')
  •  Tags:  
  • Related