views:

2508

answers:

14

Hi all.

I've always use String.IsNullOrEmpty to check for a empty string. It recently come to my attention that a " " count as not a empty string. For example,

 Dim test As String = " "
    If String.IsNullOrEmpty(test) Then
        MessageBox.Show("Empty String")
    Else
        MessageBox.Show("Not Emtpy String")
    End If

It will show "Not Empty String". So how do we check for " " or " " in a string?

edit: I wasn't aware that " " count as character.

A: 

Try

Dim test As String = " "
If String.IsNullOrEmpty(test.Trim()) Then
    MessageBox.Show("Empty String")
Else
    MessageBox.Show("Not Emtpy String")
End If

Hope that helps,

Steve

Stephen Newman
will throw an exception on Trim() with null
Andrew Robinson
Yeah, I think that was flagged higher up the chain :)
Stephen Newman
+2  A: 

The problem is you need to trim the string, however if you call trim() on a null string you will get an error.

string.IsNullOrEmpty(s.Trim())

This will error out.

You will need to do something like

if (Not string.IsNullOrEmpty(s) AndAlso s.Trim()!=string.Empty)

This will verify that the string isn't null or empty, if has something it will trim and then verify its not empty.

Edit

Thanks Slough for helping me with my VB syntax. I'm a C# guy need to brush up on vb's syntax

JoshBerke
Use ANDALSO instead of AND
dr. evil
A: 

Perhaps you just want to trim the string (of spaces) before checking it?

Dim test As String = " "
If test.Trim().Length = 0 Then // Best option as long as string is guaranteed not to be null.
//  If test = Nothing OrElse test.Trim().Length = 0 Then // If string can be null.
    MessageBox.Show("Empty String")
Else
    MessageBox.Show("Not Emtpy String")
End If
Noldorin
Also, note that you can test for `test.Trim() == string.Empty`. It's a matter of readability for you personally (I don't believe there's any performance different, as both checks probably get optimised).
Noldorin
Except that is test is null ... sorry Nothing in VB.NET it will crash.
Petar Petrov
@Petar: Read the commented line. :)
Noldorin
+6  A: 

An " " is an ASCII 32 value, it is no different from any other ASCII character except it "looks" blank.

Petras
+11  A: 

Try this method to check for blank strings. It is different from the Trim() versions in that it does not allocate a new string. It also uses a more expanded notion of whitespace.

Public Function IsNullOrBlank(ByVal str as String) As Boolean
  if String.IsNullOrEmpty(str) Then
    Return True
  End IF
  For Each c In str
    IF Not Char.IsWhiteSpace(c) Then
      Return False
    End If
  Next
  Return True
End Function
JaredPar
Ohh the top of your head do you know what the associated cost of using Trim vs this?
JoshBerke
@Josh no, that would require a profiler :). I imagine they are close to the same speed as they do roughly the same thing. The main difference is the allocation of the string
JaredPar
+1  A: 

In VB.NET you'll need to use a test like this:

If String.IsNullOrEmpty(test) OrElse String.IsNullOrEmpty(test.Trim()) Then

The OrElse prevents the NullException from occurring on the test.Trim()

Gavin Miller
interesting, is there a C# equivalent to OrElse?
Neil N
VB uses Or and OrElse where as C# uses | and ||
Martin Brown
This has one more test of null than it needs. Better to do: If (s Is Nothing OrElse s.Trim() = String.Empty) Then
Martin Brown
@Martin - Is the extra null test a difference worth worrying about?
Gavin Miller
It's not, but Trim() can be an expensive operation compared to checking every character for Char.IsWhiteSpace().
Phong
A: 

As was mentioned, calling Trim() will throw a NullReferenceException if the string is null. I sometimes use Regex.IsMatch(test, "^ +$") (hope I have the parameter order right) to test for one or more spaces. The ^ and $ make sure you're matching the entire string.

John M Gant
A: 

You can add an extension method such as was discussed here and keep the same ease of use you previously had with IsNullOrEmpty.

sipwiz
Sigh... Mine is exactly the same answer as Martin's below. Cutting and pasting gets an up vote while providing a link gets a downvote. Must be someone using Lynx who gets irritated by hyperlinks.
sipwiz
+1  A: 
public static bool IsNullOrWhite(string s)
{
  if (String.IsNullOrEmpty(s))
    return true;

  for (int i = 0; i < s.Length; i++)
 if (!Char.IsWhiteSpace(s, i))
      return false;

  return true;
}
François
A: 

If you really need to treat strings containing only whitespace character the same as empty or null strings, then you could use an extension method like this one (sorry, it's in C#):

namespace ExtensionMethods
{
    public static class StringExtensions
    {
     public static bool IsNullOrEmptyOrWhitespace(this string str)
     {
      if (string.IsNullOrEmpty(str)) return true;
      return (str.Trim().Length == 0);
     }
    }
}

This allows you to write:

using ExtensionMethods;

string s1 = "  ";
string s2 = "some string";

s1.IsNullOrEmptyOrWhitespace(); //-> returns true
s2.IsNullOrEmptyOrWhitespace(); //-> returns false
M4N
A: 
If String.IsNullOrEmpty(str) OrElse str.Trim().Length = 0 Then
  ' ..
End If

The following may not work sometime if the str is null as calling a method on null will result in exception. If String.IsNullOrEmpty(str.Trim()) Then ' exception sometimes ... End If

Niran
A: 
If test Is Nothing OrElse test.Trim().Length = 0 Then ...
Mark Cidade
A: 

Itrecentlycametomyattentionthatspacecharactersareindeednotirrelevant.

Ingo
+2  A: 

String.IsNullOrWhiteSpace is in the BCL in .NET 4

Phil Devaney