markzzz
markzzz

Reputation: 47945

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

I mean :

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

how can i do it faster in C#?

Upvotes: 7

Views: 13005

Answers (3)

Guffa
Guffa

Reputation: 700192

You can check if it only contains digits:

if (theString.All(Char.IsDigit))

Upvotes: 9

Jon Skeet
Jon Skeet

Reputation: 1499880

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"?

Upvotes: 5

SLaks
SLaks

Reputation: 887275

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

Upvotes: 19

Related Questions