Soy un principiante en el desarrollo de software Android. Estoy haciendo una aplicación de calculadora para probar mis habilidades. En una calculadora hay 0-9 numéricos y algunos otros operadores como +, -, *, / etc. En el momento de la funcionalidad Igual, debo asegurarme de que la última cadena de TextView tenga cualquier número (0-9) , no cualquier operador.
Mi igual diversión es así:
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() } }
Necesitas usar coincidencias de expresiones regulares de Kotlin
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)
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/ends-with.html
fun String.endsWith( suffix: String, ignoreCase: Boolean = false ): Boolean
Devuelve verdadero si esta cadena termina con el sufijo especificado.
Gracias a todos. Hice mi propia solución.
Aquí está el código que he escrito:
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 } }