[SOLVED] Fastest way to check if string contains only digits in C#

Issue

I know a few ways of how to check if a string contains only digits:
RegEx, int.parse, tryparse, looping, etc.

Can anyone tell me what the fastest way to check is?

I need only to CHECK the value, no need to actually parse it.

By "digit" I mean specifically ASCII digits: 0 1 2 3 4 5 6 7 8 9.

This is not the same question as Identify if a string is a number, since this question is not only about how to identify, but also about what the fastest method for doing so is.

Solution

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.

Answered By – jakobbotsch

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *