I know a few ways how to check this.
regex,int.parse
,tryparse
,looping.
can anyone tell me what is the fastest way to check?
the nee
bool IsDigitsOnly(string str)
{
foreach (char c in str)
{
if (c < '0' || c > '9')
return false;
}
return true;
}
Will probably be the fastest way to do it.
This might be coming super late!, but I'm sure it will help someone, as it helped me.
private static bool IsDigitsOnly(string str)
{
return str.All(c => c >= '0' && c <= '9');
}
if it is a single string :
if (str.All(Char.IsDigit))
{
// string contains only digits
}
if it is a list of strings :
if (lstStr.All(s => s.All(Char.IsDigit)))
{
// List of strings contains only digits
}
You can try using Regular Expressions by testing the input string to have only digits (0-9) by using the .IsMatch(string input, string pattern)
method in C#.
using System;
using System.Text.RegularExpression;
public namespace MyNS
{
public class MyClass
{
public void static Main(string[] args)
{
string input = Console.ReadLine();
bool containsNumber = ContainsOnlyDigits(input);
}
private bool ContainOnlyDigits (string input)
{
bool containsNumbers = true;
if (!Regex.IsMatch(input, @"/d"))
{
containsNumbers = false;
}
return containsNumbers;
}
}
}
Regards
What about char.IsDigit(myChar)
?
You could simply do this using LINQ
return str.All(char.IsDigit);
.All
returns true for empty strings and exception for null strings.char.IsDigit
is true for all Unicode characters.