In C#, how to check whether a string contains an integer?

148,597

Solution 1

The answer seems to be just no.

Although there are many good other answers, they either just hide the uglyness (which I did not ask for) or introduce new problems (edge cases).

Solution 2

You could use char.IsDigit:

     bool isIntString = "your string".All(char.IsDigit)

Will return true if the string is a number

    bool containsInt = "your string".Any(char.IsDigit)

Will return true if the string contains a digit

Solution 3

Assuming you want to check that all characters in the string are digits, you could use the Enumerable.All Extension Method with the Char.IsDigit Method as follows:

bool allCharactersInStringAreDigits = myStringVariable.All(char.IsDigit);

Solution 4

Maybe this can help

string input = "hello123world";
bool isDigitPresent = input.Any(c => char.IsDigit(c));

answer from msdn.

Solution 5

You can check if string contains numbers only:

Regex.IsMatch(myStringVariable, @"^-?\d+$")

But number can be bigger than Int32.MaxValue or less than Int32.MinValue - you should keep that in mind.

Another option - create extension method and move ugly code there:

public static bool IsInteger(this string s)
{
   if (String.IsNullOrEmpty(s))
       return false;

   int i;
   return Int32.TryParse(s, out i);
}

That will make your code more clean:

if (myStringVariable.IsInteger())
    // ...
Share:
148,597
Marcel
Author by

Marcel

I am an experienced software developer for both technical and business software, mainly in C#/.NET. Most professional projects are web applications or web services in the telecommunications field, for large corporate customers. I work and live in Switzerland. In my spare time I build and hack hardware stuff and occasionally, I blog on https://qrys.ch about it.

Updated on October 17, 2020

Comments

  • Marcel
    Marcel over 3 years

    I just want to know, whether a String variable contains a parsable positive integer value. I do NOT want to parse the value right now.

    Currently I am doing:

    int parsedId;
    if (
        (String.IsNullOrEmpty(myStringVariable) ||
        (!uint.TryParse(myStringVariable, out parsedId))
    )
    {//..show error message}
    

    This is ugly - How to be more concise?

    Note: I know about extension methods, but I wonder if there is something built-in.