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
You can do this in a one line LINQ statement. OK, I realise this is not necessarily the fastest, so doesn't technically answer the question, but it's probably the easiest to write:
str.All(c => c >= '0' && c <= '9')
Function with empty validation:
public static bool IsDigitsOnly(string str)
{
return !string.IsNullOrEmpty(str) && str.All(char.IsDigit);
}
Here's some benchmarks based on 1000000 parses of the same string:
Updated for release
stats:
IsDigitsOnly: 384588
TryParse: 639583
Regex: 1329571
Here's the code, looks like IsDigitsOnly is faster:
class Program
{
private static Regex regex = new Regex("^[0-9]+$", RegexOptions.Compiled);
static void Main(string[] args)
{
Stopwatch watch = new Stopwatch();
string test = int.MaxValue.ToString();
int value;
watch.Start();
for(int i=0; i< 1000000; i++)
{
int.TryParse(test, out value);
}
watch.Stop();
Console.WriteLine("TryParse: "+watch.ElapsedTicks);
watch.Reset();
watch.Start();
for (int i = 0; i < 1000000; i++)
{
IsDigitsOnly(test);
}
watch.Stop();
Console.WriteLine("IsDigitsOnly: " + watch.ElapsedTicks);
watch.Reset();
watch.Start();
for (int i = 0; i < 1000000; i++)
{
regex.IsMatch(test);
}
watch.Stop();
Console.WriteLine("Regex: " + watch.ElapsedTicks);
Console.ReadLine();
}
static bool IsDigitsOnly(string str)
{
foreach (char c in str)
{
if (c < '0' || c > '9')
return false;
}
return true;
}
}
Of course it's worth noting that TryParse does allow leading/trailing whitespace as well as culture specific symbols. It's also limited on length of string.
public bool CheckforDigits(string x)
{
int tr;
return x.All(r=> int.TryParse(r.ToString(), out tr));
}
Very Clever and easy way to detect your string is contains only digits or not is this way:
string s = "12fg";
if(s.All(char.IsDigit))
{
return true; // contains only digits
}
else
{
return false; // contains not only digits
}
I like Linq and to make it exit on first mismatch you can do this
string str = '0129834X33';
bool isAllDigits = !str.Any( ch=> ch < '0' || ch > '9' );