Petkov Alexander
Petkov Alexander

Reputation: 65

Check a string for letters or whitespaces C#

I have already checked the similar past questions but did not find the exact piece of code. I found only regex solution.

I am looking for a way to use Boolean to check whether my string is build only from letters and whitespaces or it includes other characters. I want to use char.isletter and char.whitespace.

Upvotes: -1

Views: 4032

Answers (2)

Tobias Tengler
Tobias Tengler

Reputation: 7454

You could use System.Linq's All():

bool onlyLettersAndWhitespace = input.All(i => char.IsLetter(i) || char.IsWhiteSpace(i));

Just for completeness here's the RegEx version:

bool onlyLettersAndWhitespace = Regex.IsMatch(input, @"\A[\p{L}\s]+\Z");

Example

Upvotes: 1

Ousmane D.
Ousmane D.

Reputation: 56423

you can use Linq All:

bool onlyLettersOrWhiteSpace = str.All(c => char.IsWhiteSpace(c) || char.IsLetter(c));

using System.Linq required.

Upvotes: 4

Related Questions