Nahum Litvin Nahum Litvin - 3 months ago 8
C# Question

Fastest way to check if string contains only digits

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 need is to only CHECK no need to actually parse.

this is not the same question as: How do I identify if a string is a number?

the question is not only about how identify.
but about what is the fastest method.

Answer
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.

Comments