Проверить является ли строка числом kotlin

Kotlin: проверьте, является ли строка числовой

Есть ли простой способ проверить, является ли ввод пользователя числовым? Использование регулярных выражений и исключений здесь кажется слишком сложным.

6 ответов

Вместо того, чтобы делать это с String сам по себе является CharSequence, вы можете проверить, все ли символы принадлежат определенному диапазону.

val integerChars = '0'..'9' fun isNumber(input: String): Boolean < var dotOccurred = 0 return input.all < it in integerChars || it == '.' && dotOccurred++ < 1 >> fun isInteger(input: String) = input.all < it in integerChars >fun main() < val input = readLine()!! println("isNumber: $") println("isInteger: $") > 
100234 isNumber: true isInteger: true 235.22 isNumber: true isInteger: false 102948012120948129049012849102841209849018 isNumber: true isInteger: true a isNumber: false isInteger: false 

Он также эффективен, нет выделения памяти и возвращается, как только обнаруживается какое-либо неудовлетворительное условие.

Вы также можете включить проверку отрицательных чисел, просто изменив логику, если дефис является первой буквой, вы можете применить условие для subSequence(1, length) пропуск первого символа.

Просто используйте: text.isDigitsOnly() в котлине.

объединив все полезные комментарии и поместив их в контекст входного потока, вы можете использовать это, например:

fun readLn() = readLine()!! fun readNumericOnly() < println("Enter a number") readLn().toDoubleOrNull()?.let < userInputAsDouble ->println("user input as a Double $userInputAsDouble") println("user input as an Int $") > ?: print("Not a number") > readNumericOnly() 
user input as a Double 10.0 user input as an Int 10 
user input as a Double 0.1 user input as an Int 0 

Что ж, все ответы здесь лучше всего подходят для их собственных сценариев: но не все строки являются числовыми цифрами, они могут иметь десятичные указатели (-) и (.).

Читайте также:  Создание apk из python

Итак, чтобы добиться этого, я сделал коктейль из всех ответов, предложенных ниже, а также из других сообщений, которые — выглядят следующим образом:

fun isPosOrNegNumber(s: String?) : Boolean < return if (s.isNullOrEmpty()) false else< if(s.first()=='-' && s.filter < it == '.' >.count() > else s.all > > 

Вышеупомянутый код хорошо справляется со своей задачей. Но потом меня поразило, что kotlin еще лучше справляется с сопоставлением регулярного выражения, и вуаля решение стало простым и элегантным, как показано ниже:

fun isPosOrNegNumber(s: String?) : Boolean < val regex = """^(-)?5((\.)6)$""".toRegex() return if (s.isNullOrEmpty()) false else regex.matches(s) > 

Этот образец регулярного выражения предназначен только для числовых форматов США, но если вы хотите использовать числовые форматы ЕС, просто замените ‘.’ с участием ‘,’

Bdw. если числа содержат запятые, просто замените его при отправке в этот метод или лучше сформируйте шаблон регулярного выражения с запятыми в нем.

Источник

How to use Kotlin to find whether a string is numeric?

I’d like to use a when() expression in Kotlin to return different values from a function. The input is a String , but it might be parsable to an Int , so I’d like to return the parsed Int if possible, or a String if it is not. Since the input is a String , I cannot use the is type check expression. Is there any idiomatic way to achieve that? My problem is what the when() expression should look like, not about the return type.

Functions can only have 1 return type. Perhaps return Int? and make it null if the input wasn’t numeric. Or maybe throw an exception if the input wasn’t numeric. There are many ways to go about this. — Look at the myString.toInt() extension function.

@byxor (& Todd) the function may return a generic object with 2 attributes of different types (int / string), one being null depending on the input value type

Sorry if I’m unclear, my problem is how the when expression should look like, not about the return type.

@uzilan not sure, but this page details use-cases for the when() statement : kotlinlang.org/docs/reference/control-flow.html

7 Answers 7

Version 1 (using toIntOrNull and when as requested)

fun String.intOrString(): Any < val v = toIntOrNull() return when(v) < null ->this else -> v > > "4".intOrString() // 4 "x".intOrString() // x 

Version 2 (using toIntOrNull and the elvis operator ?: )

when is actually not the optimal way to handle this, I only used when because you explicitly asked for it. This would be more appropriate:

fun String.intOrString() = toIntOrNull() ?: this 

Version 3 (using exception handling):

fun String.intOrString() = try < // returns Any toInt() >catch(e: NumberFormatException)

The toIntOrNull function in the kotlin.text package (in kotlin-stdlib ) is probably what you’re looking for:

fun String.toIntOrNull(): Int? (source) 

Platform and version requirements: Kotlin 1.1

Parses the string as an Int number and returns the result or null if the string is not a valid representation of a number.

fun String.toIntOrNull(radix: Int): Int? (source) 

Platform and version requirements: Kotlin 1.1

Parses the string as an Int number and returns the result or null if the string is not a valid representation of a number.

fun isInteger(str: String?) = str?.toIntOrNull()?.let < true >?: false 

Even if this one is the right answer, it is a general good conduct to explain why this is the answer to follow.

Thanks, but my question was (and I’m sorry if I was unclear) about using when, since I was trying to understand it at the time.

This is correct but you have to make sure the numbers you are working with are not larger than Integer or this will return false since it cannot convert it into an Int even tho its numeric. To check if a string is numeric you should use Long or Double to make the function work in more scenarios.

fun isNumeric(str: String) = str.all

As @coolMind point out, if you want to filter +/-

fun isNumeric(str: String): Boolean = str .removePrefix("-") .removePrefix("+") .all

The performance would be similar

What I like about this solution is that it does not matter how long the string is. Ints have a max value in Kotlin, which I might want to exceed

If you want to check if it is numeric (Int) the string and do something a simple solution could be:

if (myString.toIntOrNull() != null) < //Write your code you want to execute if myString is (Int) >else < //Write your code you want to execute if myString is (not Int) >

Sharing Regex matches solution, repost from my answer here

Best suited solution if negative and positive number which can be formatted with ‘-‘ and ‘.’

below method returns true if formatted string number matches the regex pattern

fun isPosOrNegNumber(s: String?) : Boolean < val regex = """^(-)?1((\.)9)$""".toRegex() return if (s.isNullOrEmpty()) false else regex.matches(s) > 

enter image description here

Above sample regex is only for US number formats but if you want to use EU number formats then just replace ‘.’ with ‘,’ in regex pattern string

Note:. if the numbers contain commas then just replace it while sending to this method or better form a regex pattern with commas in it.

Источник

Kotlin: check if string is numeric

Is there a simple way to check if user’s input is numeric? Using regexes and exceptions seems too complicated here.

I’ve found one way to check if input is integer here: stackoverflow.com/questions/48116753 but that doesn’t answer my question fully. It’s writing own function: fun isInteger(str: String?) = str?.toIntOrNull()?.let < true >?: false

String.toIntOrNull() is probably the simplest way to do this check, because it hides the exception check if the conversion fails and gives you an int if it could be converted or null if it couldn’t. So the function you noted is totally valid.

6 Answers 6

The method mentioned above will work for a number

Instead of doing that since String itself is a CharSequence, you can check if all the character belong to a specific range.

val integerChars = '0'..'9' fun isNumber(input: String): Boolean < var dotOccurred = 0 return input.all < it in integerChars || it == '.' && dotOccurred++ < 1 >> fun isInteger(input: String) = input.all < it in integerChars >fun main() < val input = readLine()!! println("isNumber: $") println("isInteger: $") > 
100234 isNumber: true isInteger: true 235.22 isNumber: true isInteger: false 102948012120948129049012849102841209849018 isNumber: true isInteger: true a isNumber: false isInteger: false 

Its efficient as well, there’s no memory allocations and returns as soon as any non-satisfying condition is found.

You can also include check for negative numbers by just changing the logic if hyphen is first letter you can apply the condition for subSequence(1, length) skipping the first character.

So as a general rule, don’t mention «above» in an answer; answer order changes when your answer is accepted or upvoted 😉

@nayriz Technically 0 == 0. == .0 == . == 0.0 == 0.00 == .00 etc (not taking significant figures into account), also calculator on my android assumes . as 0, .x6=0 x-6=-6 etc.

Simply use : text.isDigitsOnly() in kotlin.

joining all the useful comments and putting it in a input stream context, you can use this for example:

fun readLn() = readLine()!! fun readNumericOnly() < println("Enter a number") readLn().toDoubleOrNull()?.let < userInputAsDouble ->println("user input as a Double $userInputAsDouble") println("user input as an Int $") > ?: print("Not a number") > readNumericOnly() 
user input as a Double 10.0 user input as an Int 10 
user input as a Double 0.1 user input as an Int 0 

Well all the answers here are best suited for their own scenarios: But not all string are numeric digits it can have (-) and (.) decimal pointers.

So to accomplish this I made a cocktail of all the answers suggested below and from other posts as well which — looks like below :

fun isPosOrNegNumber(s: String?) : Boolean < return if (s.isNullOrEmpty()) false else< if(s.first()=='-' && s.filter < it == '.' >.count() > else s.all > > 

Above code does a good job for its purpose. But then it struck me kotlin does an even better job with matching a regex and voila the solution became simple and elegant as below :

fun isPosOrNegNumber(s: String?) : Boolean < val regex = """^(-)?5((\.)6)$""".toRegex() return if (s.isNullOrEmpty()) false else regex.matches(s) > 

This sample regex is only for US number formats but if you want to use EU number formats then just replace ‘.’ with ‘,’

Bdw. if the numbers contain commas then just replace it while sending to this method or better form a regex pattern with commas in it.

Источник

Программа Kotlin для проверки, является ли строка числовой

В этой программе вы изучите различные методы проверки, является ли строка числовой или нет в Kotlin.

Пример 1. Проверьте, является ли строка числовой.

import java.lang.Double.parseDouble fun main(args: Array) ( val string = "12345s15" var numeric = true try ( val num = parseDouble(string) ) catch (e: NumberFormatException) ( numeric = false ) if (numeric) println("$string is a number") else println("$string is not a number") )

Когда вы запустите программу, вывод будет:

В приведенной выше программе у нас есть String именованная строка, содержащая проверяемую строку. У нас также есть логическое значение numeric, которое сохраняет, является ли окончательный результат числовым или нет.

Для того, чтобы проверить , если строка содержит только цифры, в блоке попробовать, мы используем Double «s parseDouble() метод , чтобы преобразовать строку в Double .

Если он вызывает ошибку (т.е. NumberFormatException ошибку), это означает, что строка не является числом, а для числового значения установлено значение false . В противном случае это число.

Однако, если вы хотите проверить, нужно ли для ряда строк изменить его на функцию. И логика основана на выдаче исключений, это может быть довольно дорого.

Вместо этого мы можем использовать возможности регулярных выражений, чтобы проверить, является ли строка числовой или нет, как показано ниже.

Пример 2: проверьте, является ли строка числовой или не использует регулярные выражения (регулярное выражение)

fun main(args: Array) ( val string = "-1234.15" var numeric = true numeric = string.matches("-?\d+(\.\d+)?".toRegex()) if (numeric) println("$string is a number") else println("$string is not a number") )

Когда вы запустите программу, вывод будет:

В приведенной выше программе вместо использования блока try-catch мы используем регулярное выражение, чтобы проверить, является ли строка числовой или нет. Это делается с помощью matches() метода String .

  • -? допускает ноль или более — отрицательных чисел в строке.
  • \d+ проверяет, что в строке должно быть хотя бы 1 или более чисел ( \d ).
  • (\.\d+)? допускает ноль или более заданного шаблона, (\.\d+) в котором
    • \. проверяет, содержит ли строка . (десятичные точки) или нет
    • Если да, за ним должно быть указано хотя бы одно или несколько чисел \d+ .

    Вот эквивалентный код Java: программа на Java для проверки, является ли строка числовой.

    Источник

Оцените статью