Reputation: 47945
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
Reputation: 700192
You can check if it only contains digits:
if (theString.All(Char.IsDigit))
Upvotes: 9
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