Extract numerical value of a string with kotlin

1

How to extract the value from a string until you find a number, for example:

val cadena = "512ASND"

I want to get the value "512" of that string!

    
asked by Oscar Byron 03.09.2018 в 19:34
source

2 answers

1

You can use a method which reviews each element of the chain and only obtains those that are numerical values, this would be the method:

fun getNumericValues(cadena: String): String {

    val sb = StringBuilder()

    for (i in cadena.indices) {
        var numeric = true
        try {
            val num = parseDouble(cadena[i].toString())
        } catch (e: NumberFormatException) {
            numeric = false
        }

        if (numeric) {
            //es un valor numerico.
            sb.append(cadena[i].toString())
        } else {
            //no es valor numerico.
        }

    }

    return sb.toString();
}

this is an example of use:

val cadena = "512ASND"
println(getNumericValues(cadena));

to get as output:

512

Performing a bit of code I got this other method which looks for if each element of the string is of type String then adds it to a MutableList

fun getNumericValues(cadena: String): String {

      val result : MutableList<Int> = mutableListOf<Int>()
        var numberStr = ""
        for(i : Int in 0 until cadena.length){
            val c: Char = cadena[i]

            if(c in '0'..'9'){
                numberStr += c
                if(i == cadena.length - 1){
                    result.add(numberStr.toInt())
                }
            }else if(!numberStr.isNullOrBlank()){
                result.add(numberStr.toInt())
                numberStr = ""
            }

        }

        return result.joinToString(separator , "")
    }

this is an example of use:

val cadena = "512ASND"
println(getNumericValues(cadena));

to get as output:

512
    
answered by 04.09.2018 в 17:00
0

With regular expressions you can achieve it, just create an expression from a string:

val regex = """[0-9]+""".toRegex()

then with the find method you search for the first match.

val number = regex.find("512ASND")
    
answered by 03.09.2018 в 19:41