How I can check if my string only contain numbers?
I don't remember. Something like isnumeric?
How I can check if my string only contain numbers?
I don't remember. Something like isnumeric?
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
Your question is not clear. Is .
allowed in the string? Is ¼
allowed?
string source = GetTheString();
//only 0-9 allowed in the string, which almost equals to int.TryParse
bool allDigits = source.All(char.IsDigit);
bool alternative = int.TryParse(source,out result);
//allow other "numbers" like ¼
bool allNumbers = source.All(char.IsNumber);
If you want to use Regex you would have to use something like this:
string regExPattern = @"^[0-9]+$";
System.Text.RegularExpressions.Regex pattern = new System.Text.RegularExpressions.Regex(regExPattern);
return pattern.IsMatch(yourString);
public bool IsNumeric(string str)
{
return str.All(c => "0123456789".Contains(c);
}