How I can check if my string only contain numbers?
I don't remember. Something like isnumeric?
Use the test() method on the following regular expression to check if a string contains only letters and numbers - /^[A-Za-z0-9]*$/ . The test method will return true if the regular expression is matched in the string and false otherwise.
Python String isnumeric() Method The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .
To check if a string contains any letter, use the test() method with the following regular expression /[a-zA-Z]/ . The test method will return true if the string contains at least one letter and false otherwise. Copied!
Using Character.isDigit(char ch). If the character is a digit then return true, else return false.
Just check each character.
bool IsAllDigits(string s) { foreach (char c in s) { if (!char.IsDigit(c)) return false; } return true; }
Or use LINQ.
bool IsAllDigits(string s) => s.All(char.IsDigit);
If you want to know whether or not a value entered into your program represents a valid integer value (in the range of int
), you can use TryParse()
. Note that this approach is not the same as checking if the string contains only numbers.
bool IsAllDigits(string s) => int.TryParse(s, out int i);
You could use Regex or int.TryParse.
See also C# Equivalent of VB's IsNumeric()
int.TryParse() method will return false for non numeric strings
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With