Determine if a string starts with a number in Kotlin
This post will check if a string starts with a number or not in Kotlin.
A simple solution to check if the first character of the string is a digit is using the isDigit() function, which provides support for all Unicode digits.
|
1 2 3 4 5 |
fun main() { val s = "7 Wonders of the World" println(s.isNotEmpty() && s[0].isDigit()) // true } |
Another solution is to extract the first character from the given string and check if that character falls under the numeric ASCII range or not.
|
1 2 3 4 5 |
fun main() { val s = "7 Wonders of the World" println(s.isNotEmpty() && s[0] >= '0' && s[0] <= '9') // true } |
In Kotlin, two comparisons should be converted to a range check:
|
1 2 3 4 5 |
fun main() { val s = "7 Wonders of the World" println(s.isNotEmpty() && s[0] in '0'..'9') // true } |
Here’s an alternate version using the any() function. It returns true if at least one element matches the supplied predicate.
|
1 2 3 4 5 |
fun main() { val s = "7 Wonders of the World" println(s.isNotEmpty() && ('0'..'9').any { it == s[0] }) // true } |
Note that all the above solutions validate that the string is not empty to avoid string index out of range exception. That’s all about checking if a string starts with a number in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)