.Net: Empty string is not clear space character?

16,014

Solution 1

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

Solution 2

String.IsNullOrWhiteSpace is in the BCL in .NET 4

Solution 3

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

Solution 4

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

Solution 5

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()

Share:
16,014
Jack
Author by

Jack

Updated on July 09, 2022

Comments

  • Jack
    Jack almost 2 years

    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.