Pradvaar cruz
Pradvaar cruz

Reputation: 291

Check string for all digits and if any white space using Linq

I'm checking a string value using Linq, if it has all digits using the following query:

bool isAllDigits = !query.Any(ch => ch < '0' || ch > '9');

But if user enters a space, along with digits (eg: "123 456", "123456 ") this check fails. Is there a way that I can check for white spaces as well?

I don't want to trim out the white spaces, because I use this text box to search with text, which contains spaces in between.

Upvotes: 1

Views: 2303

Answers (2)

maccettura
maccettura

Reputation: 10818

Try this:

bool isAllDigits = query.All(c => char.IsWhiteSpace(c) || char.IsDigit(c));

These methods are built into the framework and instead of rolling your own checks, I would suggest using these.

I made a fiddle here to demonstrate.

EDIT

As pointed out in the comments, char.IsDigit() will return true for other "digit" characters as well (i.e not just '0'-'9', but also other language/culture number representations as well). The full list (I believe) can be found here.

In addition, char.IsWhiteSpace() will also return true for various types of whitespace characters (see the docs for more details).

If you want to only allow 0-9 and a regular 'ol space character, you can do this:

bool isAllDigits = s.All(c => (c < 57 && c > 48) || c == 32);

I am using the decimal values of the ASCII characters (for reference), but you could also continue doing it the way you are currently:

bool isAllDigits = s.All(c => (c < '9' && c > '0') || c == ' ');

Either way is fine, the important thing to note is the parentheses. You want any character that is greater than 0, but less than 9 OR just a single space.

Upvotes: 5

Broom
Broom

Reputation: 596

bool isAllDigits = !query.Any(ch => (ch < '0' || ch > '9') && ch != ' ');

Upvotes: 0

Related Questions