0

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.

  • Can you share some sample input strings and the expected output for each of them? Can you also share whatever code you have written for this and explain what exact issue you are facing in that? – Chetan Dec 08 '18 at 13:48
  • what's wrong with RegEx BTW? – Rahul Dec 08 '18 at 13:48
  • 1
    Like `"ABC DEF".All(c => char.IsLetter(c) || char.IsWhiteSpace(c))`? – Rotem Dec 08 '18 at 13:50
  • If you want boolean then `Regex.IsMatch()` is also suitable for you. – er-sho Dec 08 '18 at 13:50
  • Please provide more information about what type of comparison you're trying to do. `bool` is a value type in C#. Saying you want to use boolean to check if your string contains spaces is like saying you want to use integers to check if a number is a certain value: it tells us nothing about how you want to do the comparison. – Patrick Tucci Dec 08 '18 at 13:57

2 Answers2

4

you can use Linq All:

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

using System.Linq required.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
1

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

Tobias Tengler
  • 6,848
  • 4
  • 20
  • 34
  • FYI - the solutions don't produce the same result with different languages - none latin characters - https://dotnetfiddle.net/Ntguvm – Rand Random Dec 08 '18 at 14:03
  • @RandRandom yep, that's true. Didn't thought of that. But honestly I'm not sure if there is a way to check for 'all' letters with Regex (w/o making it horribly long). I'm going to make it so that both produce the same result and only accept latin characters. – Tobias Tengler Dec 08 '18 at 14:20
  • FYI - https://stackoverflow.com/questions/3617797/regex-to-match-only-letters - so you could have changed the regex to `\p{L}` - https://dotnetfiddle.net/869O2I – Rand Random Dec 08 '18 at 14:32