79

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.

Marcel
  • 15,039
  • 20
  • 92
  • 150

8 Answers8

148

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

DGibbs
  • 14,316
  • 7
  • 44
  • 83
  • 7
    If `str` is equal to `"iuhs,./hu3dwuh"`, then `str.Any(char.IsDigit)` will be true. – Jeppe Stig Nielsen Aug 15 '13 at 11:47
  • 3
    I'm not the downvoter, but 1. There's no static function on the `string` class called `Any` (presumably you meant for the string variable to be called `string`, but that's not possible); 2. If you're referring to the Linq extension method `Any`, you have to call it liks this: `s.Any(c => char.IsDigit(c))`; 3. I think he wants the *whole* string to be an integer, not just to contain a digit somewhere; otherwise it makes no sense for him to use `int.TryParse`. – Magnus Grindal Bakken Aug 15 '13 at 11:48
  • 6
    @MagnusGrindalBakken Regarding your (2): No, since the signature and return type is correct, the expression `char.IsDigit` (a so-called method group) _can_ be converted to type `Func` through an implicit conversion, so that part is OK. – Jeppe Stig Nielsen Aug 15 '13 at 11:50
  • 1
    @JeppeStigNielsen Good call. I always forget about that. – Magnus Grindal Bakken Aug 15 '13 at 11:52
  • I upvoted but it would be nice if you could update your answer to be correct linq like Magnus suggested. – TroySteven Jan 28 '20 at 14:54
  • 1
    @TroySteven - He's wrong though? You don't have to use lambda syntax e.g `s.Any(x => char.IsDigit(x))` you can just pass `char.IsDigit` as a delegate, try it... https://dotnetfiddle.net/qS59c0 and the first example satisfies the 'whole string is an integer' – DGibbs Jan 28 '20 at 15:55
37

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);
dtb
  • 213,145
  • 36
  • 401
  • 431
  • 1
    What if `myStringVariable` contains digit characters from many different "scripts" from all over the world, such as Hindu-Arabic numerals combined with western numerals? – Jeppe Stig Nielsen Aug 15 '13 at 11:45
  • In that case, "۲۲۲" will give true, but parsing it as an int will throw an exception. – Matthew Watson Aug 15 '13 at 12:34
  • 1
    If you wanted to check if any of the characters was numeric and not all of them, you could use - bool anyCharactersInStringAreDigits = myStringVariable.Any(char.IsDigit); – Deano Jan 10 '14 at 16:03
33

Maybe this can help

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

answer from msdn.

panako
  • 1,064
  • 10
  • 11
  • This is wrong. It will check whether some digits are present, but not whether the string as a whole does represent an integer value. – Marcel Apr 12 '19 at 07:49
  • 10
    The requirements of the question are whether a string *Contains* parsable integer, not whether or not the entire string represents an number. – Gichamba Mar 20 '20 at 11:45
8

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())
    // ...
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • straight forward answer – Radhe Sham Nov 28 '17 at 11:49
  • Nice. I have enhanced your method to handle array of string. `public static bool IsInteger(this string[] str) { bool isInteger = false; if (str == null) return isInteger; foreach (var s in str) { if (String.IsNullOrEmpty(s)) return isInteger; int i; isInteger = Int32.TryParse(s, out i); if (isInteger == false) return isInteger; } return isInteger; }` – Ashish Kumar Jaryal Jan 16 '19 at 15:08
5

This work for me.

("your string goes here").All(char.IsDigit)
sarmad salik
  • 59
  • 1
  • 2
  • 1
    Thanks for your contribution. But however, this is a repetition of the answer @dtb already gave some years ago. – Marcel Apr 12 '19 at 07:47
4

Sorry, didn't quite get your question. So something like this?

str.ToCharArray().Any(char.IsDigit);

Or does the value have to be an integer completely, without any additional strings?

if(str.ToCharArray().All(char.IsDigit(c));
SBoss
  • 8,845
  • 7
  • 28
  • 44
3
        string text = Console.ReadLine();
        bool isNumber = false;

        for (int i = 0; i < text.Length; i++)
        {
            if (char.IsDigit(text[i]))
            {
                isNumber = true;
                break;
            }
        }

        if (isNumber)
        {
            Console.WriteLine("Text contains number.");
        }
        else
        {
            Console.WriteLine("Text doesn't contain number.");
        }

        Console.ReadKey();

Or Linq:

        string text = Console.ReadLine();

        bool isNumberOccurance =text.Any(letter => char.IsDigit(letter));
        Console.WriteLine("{0}",isDigitPresent ? "Text contains number." : "Text doesn't contain number.");
        Console.ReadKey();
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Zsolt
  • 31
  • 1
2

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

Marcel
  • 15,039
  • 20
  • 92
  • 150
  • I guess the designers of C# could introduce some new syntactic sugar for this case where we don't care about the out variable. It could look like `int.TryParse(myStringVariable, out void)` or something. The compiler should then automatically introduce a "generated" local variable of the correct type, but it would not look ugly in code. Of course the generated variable would not be accessible (should have some "crazy" illegal name). – Jeppe Stig Nielsen Aug 15 '13 at 12:01