Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string is empty or all spaces in C#

How to easily check if a string is blank or full of an undetermined amount of spaces, or not?

like image 748
Cody Avatar asked Sep 16 '11 00:09

Cody


People also ask

How do you tell if a string is all whitespace C?

C isspace() The isspace() function checks whether a character is a white-space character or not. If an argument (character) passed to the isspace() function is a white-space character, it returns non-zero integer. If not, it returns 0.

How do I check if a string has empty spaces?

Use the test() method to check if a string contains whitespace, e.g. /\s/. test(str) . The test method will return true if the string contains at least one whitespace character and false otherwise.

Is a space an empty string?

We consider a string to be empty if it's either null or a string without any length. If a string only consists of whitespace, then we call it blank. For Java, whitespaces are characters, like spaces, tabs, and so on.

How do you check if a string only contains spaces C++?

str. end() ++i) if (! isspace(i)) return false; Pseudo-code, isspace is located in cctype for C++.


2 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

like image 135
Merlyn Morgan-Graham Avatar answered Oct 19 '22 16:10

Merlyn Morgan-Graham


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); 
like image 26
Shimmy Weitzhandler Avatar answered Oct 19 '22 14:10

Shimmy Weitzhandler