How to easily check if a string is blank or full of an undetermined amount of spaces, or not?
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.
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.
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.
str. end() ++i) if (! isspace(i)) return false; Pseudo-code, isspace is located in cctype for C++.
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With