How to easily check if a string is blank or full of an undetermined amount of spaces, or not?
6 Answers
If you have .NET 4, use the string.IsNullOrWhiteSpace
method:
if(string.IsNullOrWhiteSpace(myStringValue))
{
// ...
}
If you don't have .NET 4, and you can stand to trim your strings, you could trim it first, then check if it is empty.
Otherwise, you could look into implementing it yourself:
.Net 3.5 Implementation of String.IsNullOrWhitespace with Code Contracts

- 1
- 1

- 58,163
- 16
- 128
- 183
-
1I believe in new versions it's `string.IsNullOrEmpty(YourString)` – sylverfyre Apr 25 '13 at 16:07
-
7@sylverfyre: Nope. They're two different methods and do different things. See: [`IsNullOrEmpty`](http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx) vs [`IsNullOrWhiteSpace`](http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx) – Merlyn Morgan-Graham Apr 29 '13 at 16:23
-
21This answer is incorrect as it will return true if the string is null. – Simon Bergot Aug 10 '15 at 16:06
-
4@Simon: If people to whom this difference is important can't figure that out from the name of the method, then I probably can't help them – Merlyn Morgan-Graham Aug 11 '15 at 05:55
-
Can't help them? No, @Simon is right; sure you can! `if (string.IsNullOrWhiteSpace(myStringValue) && null != myStringValue)`. Maybe show how to create an extension method `IsWhiteSpaceAndNotNull`. Unfortunately, strictly speaking, this answer lets non-spaces in, so it doesn't *precisely* answer the OP's question as written. – ruffin May 02 '18 at 14:00
-
@ruffin I believe the additions you are proposing would bloat this answer unnecessarily, wouldn't be a good pay-off, and wouldn't be doing copy-pasta coders any favors. You're free to add your own answer and find out. – Merlyn Morgan-Graham May 02 '18 at 21:23
-
2And [done](https://stackoverflow.com/a/50144605/1028230). ;^D The OP probably wanted what you provided (we may never know...), but taken literally, your answer lets in `null`, `\t`, `\r`, and `\n`, which aren't spaces. /shrug Though this basically dupes Shimmy's, adding the ability to test nulls, which extension methods can't do. – ruffin May 02 '18 at 22:48
If it's already known to you that the string is not null, and you just want to make sure it's not a blank string use the following:
public static bool IsEmptyOrWhiteSpace(this string value) =>
value.All(char.IsWhiteSpace);

- 101,809
- 122
- 424
- 632
-
9If you need to check for null and reject it, use null-conditional invocation and null-coalescing: `value?.All(char.IsWhiteSpace) ?? false` — or you can employ less fancy short-circuit evaluation: `value != null && value.All(char.IsWhiteSpace)` – Palec May 10 '17 at 11:54
If you literally need to know if the "string is blank or full of an undetermined amount of spaces", use LINQ as @Sonia_yt suggests, but use All()
to ensure that you efficiently short-circuit out as soon as you've found a non-space.
(This is give or take the same as Shimmy's, but answers the OP's question as written to only check for spaces, not any and all whitespace -- \t
, \n
, \r
, etc.)
/// <summary>
/// Ensure that the string is either the empty string `""` or contains
/// *ONLY SPACES* without any other character OR whitespace type.
/// </summary>
/// <param name="str">The string to check.</param>
/// <returns>`true` if string is empty or only made up of spaces. Otherwise `false`.</returns>
public static bool IsEmptyOrAllSpaces(this string str)
{
return null != str && str.All(c => c.Equals(' '));
}
And to test it in a console app...
Console.WriteLine(" ".IsEmptyOrAllSpaces()); // true
Console.WriteLine("".IsEmptyOrAllSpaces()); // true
Console.WriteLine(" BOO ".IsEmptyOrAllSpaces()); // false
string testMe = null;
Console.WriteLine(testMe.IsEmptyOrAllSpaces()); // false

- 16,507
- 9
- 88
- 138
-
"but you can't call an extension method on nulls" are you sure? did you try it? I'm about 80% certain you can, without issue, as long as you do null checks before access. It's just syntactic sugar for a static method after all. – Merlyn Morgan-Graham May 03 '18 at 02:30
-
1`!enumerable.Any(x => !predicate(x))` = `enumerable.All(x => predicate(x))` Just convoluted thinking. – Palec May 03 '18 at 08:00
-
@MerlynMorgan-Graham You're quite right. I'm used to `string testMe = null; testMe.IndexOf("spam");` and getting `An unhandled exception of type 'System.NullReferenceException' occurred`, but that's the "fault" of `IndexOf`, not that the string was `null`. Score one for cargo culting/[elephant whistles](https://www.newyorker.com/magazine/2009/05/25/no-more-mr-nice-guy#articleBody). "*Hey, calling string functions like `IndexOf` on null strings breaks. Better not use extension methods on null strings. [Using extension methods on non-null strings never breaks.] See?!*" (◔_◔) – ruffin May 03 '18 at 14:52
-
@Palec Yeah, Shimmy's use of `All` is better, but his answer also makes the same "mistake" as Merlyn's... the set of whitespace characters > the set of space characters. ;^) I'll edit to use `All`. The double negative looked odd when I was writing it, and I just added a comment instead of figuring out The Right Thing To Do... Fail. Just wanted to quickly show checking for null wasn't a huge burden, which Merlyn seemed to suggest it was. /shrug Thanks for the catch. – ruffin May 03 '18 at 14:58
private bool IsNullOrEmptyOrAllSpaces(string str)
{
if(str == null || str.Length == 0)
{
return true;
}
for (int i = 0; i < str.Length; i++)
{
if (!Char.IsWhiteSpace(str[i])) return false;
}
return true;
}

- 2,249
- 13
- 25
if(string.IsNullOrEmpty(myStringValue.Trim()))
Use trim() so that whitespace strings become empty. This way you only use string.IsNullOrEmpty to check for null, whitespace, and empty strings.

- 1
Try use LinQ to solve?
if(from c in yourString where c != ' ' select c).Count() != 0)
This will return true if the string is not all spaces.

- 17
-
1Too chatty and ill-performing to be useful. This always iterates the whole string, even after seeing a non-space char. [`Enumerable.All
`](https://msdn.microsoft.com/en-us/library/bb548541(v=vs.110).aspx) employs short-circuit evaluation, see [.NET reference source](https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,be4bfd025bd2724c). – Palec Jan 16 '18 at 17:41