how can I check if a string is a positive integer?

11,091

Solution 1

int x;
if (int.TryParse(str, out x) && x > 0)

Solution 2

You can check if it only contains digits:

if (theString.All(Char.IsDigit))

Solution 3

An alternative to actually parsing it is to check if the string is non-empty and only contains digits, optionally with a leading + sign if you want to allow that.

Note that this won't perform any range checking - so 9999999999999999999999999999999999 would be valid, even though it wouldn't fit into an int or a long.

You could use a regex for that, or possibly LINQ:

var nonNegative = text.Length > 0 && text.All(c => c >= '0' && c <= '9');

(This is similar to Guffa's Char.IsDigit approach, but restricts itself to ASCII digits. There are numerous non-ASCII digits in Unicode.)

Note that this will restrict it to non-negative values - not just positive values. How would you want to treat "0" and "0000"?

Share:
11,091
markzzz
Author by

markzzz

Updated on June 15, 2022

Comments

  • markzzz
    markzzz about 2 years

    I mean :

    1231 YES
    121.1241 NO
    121,1241 NO
    -121 NO
    124a NO
    

    how can i do it faster in C#?