Home > Mobile >  Android Kotlin: how to detect the last string of a TextView contains 0 to 9
Android Kotlin: how to detect the last string of a TextView contains 0 to 9

Time:01-02

Hello I'm a beginner of android software dev. I'm making a Calculator app for testing my skills. In a calculator there are 0-9 numeric and some others operators like ,-,*,/ etc. In the time of Equal functionality, I have to make sure that the last string of the TextView has any number (0-9), not any operators.

My equal fun is like that:

fun onEqual(view: View) {
    if (tv_input.text.contains("0-9")) {
        Toast.makeText(this, "Last string is a number, not operator", Toast.LENGTH_SHORT).show()
    }
}

CodePudding user response:

You need to use Kotlin regular expression matches

val lastString = "573" // input
val pattern = "-?\\d (\\.\\d )?".toRegex()
/**
-?         allows zero or more - for negative numbers in the string.
\\d        checks the string must have at least 1 or more numbers (\\d).
(\\.\\d )? allows zero or more of the given pattern (\\.\\d ) 
           In which \\. checks if the string contains . (decimal points) or not
           If yes, it should be followed by at least one or more number \\d .
**/
val isLastString = pattern.matches(lastString)

CodePudding user response:

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/ends-with.html

fun String.endsWith(
    suffix: String,
    ignoreCase: Boolean = false
): Boolean

Returns true if this string ends with the specified suffix.

CodePudding user response:

Thanks everyone. I did my own solution.

Here is the code I've wrote:

fun onEqual(view: View) {
    if (!tv_input.text.toString().equals("")) {
        val last = tv_input.text.toString()
        val lastNumber: String = last.get(last.length - 1).toString()
        Toast.makeText(this, lastNumber, Toast.LENGTH_SHORT).show()
    }else {
        return
    }
}
  • Related