C#: Fastest way to check if a string has digits only

Hello World,

This is going to be a very short one. In one of my projects recently, I had to check if a string contained only numbers and take an action based on that check. As always, a quick Google threw up a gazillion way of doing this but the challenge was to do it as fast as possible using C# and .NET.

The Choices

  1. Try to parse the string as an Int – you can run into trouble here if the string has a number that is greater than int.MaxValue
  2. Use a Regular Expression to match the string
  3. Loop through the array of characters in the string and check if each character is a digit

Stackoverflow (bless those guys 🙂 ) has a wonderful discussion and the code that works the fastest is:

static bool IsDigitsOnly(string str)
        foreach (char c in str)
            if (c < '0' || c > '9')
                return false;

        return true;

Note that in the stackoverflow discussion, there is this snippet which looks very precise:

var theString = "1241234";
var isNumbersOnly = theString.All(char.IsDigit);

But as my comment on that answer says, this approach is a tad slower than looping over the string’s characters.

Also, note that you may eventually need to convert the string to one of .NET’s numeric types in which case you would use a Parsing method. But you can save some critical time by first validating if it contains valid numeric value or not

Happy Coding!

Tagged with: ,
Posted in .NET, C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

  • Comic for July 25, 2017
    Dilbert readers - Please visit Dilbert.com to read this feature. Due to changes with our feeds, we are now making this RSS feed a link to Dilbert.com.
%d bloggers like this: