- Programming-Idioms
- Idiom #137 Check if string contains only digits
- Please choose a nickname before doing this
- Check if a String Is Numeric in Kotlin
- 1. Overview
- 2. By Parsing to Double or Int
- 3. Using Regular Expressions
- 4. Using isDigit() and all()
- 5. Conclusion
- Programming-Idioms
- Idiom #137 Check if string contains only digits
- Please choose a nickname before doing this
- Kotlin – Check if String contains only Alphabets and Digits
- Check if String contains only Alphabets and Digits in Kotlin
- Examples
- Validate ID number of Employee
- Negative Scenario
Programming-Idioms
- C
- C++
- C#
- Go
- Java
- JS
- Obj-C
- PHP
- Python
- Ruby
- Rust
- Or search :
Idiom #137 Check if string contains only digits
Set the boolean b to true if the string s contains only characters in the range ‘0’..’9′, false otherwise.
fun String?.isOnlyDigits() = !this.isNullOrEmpty() && this.all
val regex = Regex("1*") val b = regex.matches(s)
B := (for all Char of S => Char in '0' .. '9');
char b = 0; int n = strlen(s); for (int i = 0; i < n; i++) < if (! (b = (s[i] >= '0' && s[i]
bool b = true; const int n = strlen(s); for (int i = 0; i < n; ++i) < if (!isdigit(s[i])) < b = false; break; >>
(def b (every? #(Character/isDigit %) s))
bool b = false; if (! s.empty() && std::all_of(s.begin(), s.end(), [](char c)))
import std.ascii; import std.algorithm;
std.algorithm.iteration; std.ascii;
bool b = s.filter!(a => !isDigit(a)).empty;
final b = RegExp(r'^3+$').hasMatch(s);
= string:to_integer(S), B = Rest == "".
b = .true. do i=1, len(s) if (s(i:i) < '0' .or. s(i:i) >'9') then b = .false. exit end if end do
isNotDigit := func(c rune) bool < return c < '0' || c >'9' > b := strings.IndexFunc(s, isNotDigit) == -1
b := true for _, c := range s < if c < '0' || c >'9' < b = false break >>
(setf b (every #'digit-char-p s))
id nodigit=[[NSCharacterSet characterSetWithRange:NSMakeRange('0',10)].invertedSet copy]; BOOL b=![s rangeOfCharacterFromSet:nodigit].length;
var S: String; C: Char; B: Boolean; for C in S do begin B := C in ['0'..'9']; if not B then Break; end;
let b = s.bytes().all(|c| c.is_ascii_digit());
let b = s.chars().all(char::is_numeric);
let chars_are_numeric: Vec = s.chars() .map(|c|c.is_numeric()) .collect(); let b = !chars_are_numeric.contains(&false);
def onlyDigits(s: String) = s.forall(_.isDigit)
Dim x As String = "123456" Dim b As Boolean = IsNumeric(x)
Please choose a nickname before doing this
fun String?.isOnlyDigits() = !this.isNullOrEmpty() && this.all
val regex = Regex("5*") val b = regex.matches(s)
B := (for all Char of S => Char in '0' .. '9');
char b = 0; int n = strlen(s); for (int i = 0; i < n; i++) < if (! (b = (s[i] >= ‘0’ && s[i]
bool b = true; const int n = strlen(s); for (int i = 0; i < n; ++i) < if (!isdigit(s[i])) < b = false; break; >>
(def b (every? #(Character/isDigit %) s))
bool b = false; if (! s.empty() && std::all_of(s.begin(), s.end(), [](char c)))
bool b = s.filter!(a => !isDigit(a)).empty;
final b = RegExp(r'^1+$').hasMatch(s);
= string:to_integer(S), B = Rest == "".
b = .true. do i=1, len(s) if (s(i:i) < '0' .or. s(i:i) >'9') then b = .false. exit end if end do
isNotDigit := func(c rune) bool < return c < '0' || c >'9' > b := strings.IndexFunc(s, isNotDigit) == -1
b := true for _, c := range s < if c < '0' || c >'9' < b = false break >>
(setf b (every #'digit-char-p s))
id nodigit=[[NSCharacterSet characterSetWithRange:NSMakeRange('0',10)].invertedSet copy]; BOOL b=![s rangeOfCharacterFromSet:nodigit].length;
var S: String; C: Char; B: Boolean; for C in S do begin B := C in ['0'..'9']; if not B then Break; end;
let b = s.bytes().all(|c| c.is_ascii_digit());
let b = s.chars().all(char::is_numeric);
let chars_are_numeric: Vec = s.chars() .map(|c|c.is_numeric()) .collect(); let b = !chars_are_numeric.contains(&false);
def onlyDigits(s: String) = s.forall(_.isDigit)
Dim x As String = "123456" Dim b As Boolean = IsNumeric(x)
Check if a String Is Numeric in Kotlin
As a seasoned developer, you’re likely already familiar with Spring. But Kotlin can take your developer experience with Spring to the next level!
- Add new functionality to existing classes with Kotlin extension functions.
- Use Kotlin bean definition DSL.
- Better configure your application using lateinit.
- Use sequences and default argument values to write more expressive code.
By the end of this talk, you’ll have a deeper understanding of the advanced Kotlin techniques that are available to you as a Spring developer, and be able to use them effectively in your projects.
1. Overview
In this tutorial, we’ll look at some common ways to check if a String is numeric. First, we’ll talk about parsing methods and using regular expressions.
Finally, we’ll look at another method that only detects positive integers.
2. By Parsing to Double or Int
One way to check if a string is numeric is to parse it as a Double or Int (or other built-in numeric types). In case this parsing attempt doesn’t return null, we can safely assume that a String is a number:
fun isNumericToX(toCheck: String): Boolean
This method can handle Double and all the numeric types like Int, Float, and so on:
assertTrue < isNumeric("11") >assertTrue < isNumeric("-11") >assertTrue < isNumeric("011") >assertTrue < isNumeric("11.0F") >assertTrue < isNumeric("11.0D") >assertTrue < isNumeric("11.234") >assertTrue < isNumeric("11.234e56") >assertTrue
This method is quite versatile and can handle all numeric types. However, we can also perform checks for the other numeric types. We can do so by replacing toDoubleOrNull with other conversion methods:
Notably, we can call each of these conversion methods on all numeric types in Kotlin.
3. Using Regular Expressions
We can also use regular expressions to check if a String is numeric:
fun isNumeric(toCheck: String): Boolean
Here, we use a regex to check if the String is a number. The regex is structured to match a decimal number.
- -? – We check if the number has zero or one minus (“-“) symbol at the start.
- 2 – We check if there are one or more digits in a String. This fails if there are no numbers. Notably, this only matches 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. However, if we want to look for other Unicode numerals, we can use “\d” instead of “5”.
- (\\.6+)? – We check if there’s a decimal (“.”) symbol; if so, it must be followed by at least one digit.
4. Using isDigit() and all()
Another way to check if a String contains only digits is to use a combination of all and isDigit methods:
fun isNumeric(toCheck: String): Boolean < return toCheck.all < char ->char.isDigit() > >
Here, we check if each character of a String is a numeric digit. The all method returns true if all characters return true when passed to the isDigit method.
This also means that this method doesn’t work for negative or floating-point numbers.
5. Conclusion
We looked at various ways to check if a string is numeric. First, we used the various parsing functions that Kotlin has to offer (toDoubleOrNull(), toIntOrNull(), and others). This method seems the most versatile and covers the most use cases.
Later, we also looked at other options that cover relatively lesser use cases. These methods used regular expressions and Kotlin factory functions to check numeric Strings.
As always, the code samples are available over on GitHub.
Programming-Idioms
- C
- C++
- C#
- Go
- Java
- JS
- Obj-C
- PHP
- Python
- Ruby
- Rust
- Or search :
Idiom #137 Check if string contains only digits
Set the boolean b to true if the string s contains only characters in the range ‘0’..’9′, false otherwise.
val regex = Regex("9*") val b = regex.matches(s)
fun String?.isOnlyDigits() = !this.isNullOrEmpty() && this.all
B := (for all Char of S => Char in '0' .. '9');
char b = 0; int n = strlen(s); for (int i = 0; i < n; i++) < if (! (b = (s[i] >= '0' && s[i]
bool b = true; const int n = strlen(s); for (int i = 0; i < n; ++i) < if (!isdigit(s[i])) < b = false; break; >>
(def b (every? #(Character/isDigit %) s))
bool b = false; if (! s.empty() && std::all_of(s.begin(), s.end(), [](char c)))
import std.ascii; import std.algorithm;
std.algorithm.iteration; std.ascii;
bool b = s.filter!(a => !isDigit(a)).empty;
final b = RegExp(r'^2+$').hasMatch(s);
= string:to_integer(S), B = Rest == "".
b = .true. do i=1, len(s) if (s(i:i) < '0' .or. s(i:i) >'9') then b = .false. exit end if end do
isNotDigit := func(c rune) bool < return c < '0' || c >'9' > b := strings.IndexFunc(s, isNotDigit) == -1
b := true for _, c := range s < if c < '0' || c >'9' < b = false break >>
(setf b (every #'digit-char-p s))
id nodigit=[[NSCharacterSet characterSetWithRange:NSMakeRange('0',10)].invertedSet copy]; BOOL b=![s rangeOfCharacterFromSet:nodigit].length;
var S: String; C: Char; B: Boolean; for C in S do begin B := C in ['0'..'9']; if not B then Break; end;
let b = s.bytes().all(|c| c.is_ascii_digit());
let b = s.chars().all(char::is_numeric);
let chars_are_numeric: Vec = s.chars() .map(|c|c.is_numeric()) .collect(); let b = !chars_are_numeric.contains(&false);
def onlyDigits(s: String) = s.forall(_.isDigit)
Dim x As String = "123456" Dim b As Boolean = IsNumeric(x)
Please choose a nickname before doing this
val regex = Regex("2*") val b = regex.matches(s)
fun String?.isOnlyDigits() = !this.isNullOrEmpty() && this.all
B := (for all Char of S => Char in '0' .. '9');
char b = 0; int n = strlen(s); for (int i = 0; i < n; i++) < if (! (b = (s[i] >= ‘0’ && s[i]
bool b = true; const int n = strlen(s); for (int i = 0; i < n; ++i) < if (!isdigit(s[i])) < b = false; break; >>
(def b (every? #(Character/isDigit %) s))
bool b = false; if (! s.empty() && std::all_of(s.begin(), s.end(), [](char c)))
bool b = s.filter!(a => !isDigit(a)).empty;
final b = RegExp(r'^8+$').hasMatch(s);
= string:to_integer(S), B = Rest == "".
b = .true. do i=1, len(s) if (s(i:i) < '0' .or. s(i:i) >'9') then b = .false. exit end if end do
isNotDigit := func(c rune) bool < return c < '0' || c >'9' > b := strings.IndexFunc(s, isNotDigit) == -1
b := true for _, c := range s < if c < '0' || c >'9' < b = false break >>
(setf b (every #'digit-char-p s))
id nodigit=[[NSCharacterSet characterSetWithRange:NSMakeRange('0',10)].invertedSet copy]; BOOL b=![s rangeOfCharacterFromSet:nodigit].length;
var S: String; C: Char; B: Boolean; for C in S do begin B := C in ['0'..'9']; if not B then Break; end;
let b = s.bytes().all(|c| c.is_ascii_digit());
let b = s.chars().all(char::is_numeric);
let chars_are_numeric: Vec = s.chars() .map(|c|c.is_numeric()) .collect(); let b = !chars_are_numeric.contains(&false);
def onlyDigits(s: String) = s.forall(_.isDigit)
Dim x As String = "123456" Dim b As Boolean = IsNumeric(x)
Kotlin – Check if String contains only Alphabets and Digits
Check if String contains only Alphabets and Digits in Kotlin
To check if given string contains only Alphabet characters and digits in Kotlin, check if all of the characters in the string is an alphabet or digit using String.all() function and Char.isLetterOrDigit() function.
Char.isLetterOrDigit() function is used to check if the character is an alphabet or a digit.
String.all() function is used to check if all the characters in the given string satisfy the given condition.
The boolean expression to check if given string str contains only alphabets and digits is
Examples
Validate ID number of Employee
Consider that in a company ABC, the employees are given an ID which contains only alphabets and numeric digits.
In the following program, we take a string value in str , say ID of an employee and validate this string to check if it contains only only alphabets and digits.
Kotlin Program
String contains only alphabets and digits.
Negative Scenario
In the following program, we take a string in str such that there are characters other than alphabets and digits, and run the same code from the previous example.
Kotlin Program
String does not contain only alphabets and digits.
There is a whitespace character and hyphen character in the string. Therefore, the output says that the string does not contain only alphabets and digits.