Removing Spaces, the Easy Way was originally published on February 22, 2007.


There are tons of functions in so-called "standard" libraries, but sometimes the function you want just isn't there. Luckily, string functions are so simple to write that anyone can do it!

Submitted for your consideration, an example from Randy, who says, "I think the design kind of speaks for itself." The following code demonstrates how to get rid of unwanted spaces.

 

  Private Function RemoveSpace(ByVal strFldName As String) As String
      Try
          Dim i As Integer
          RemoveSpace = ""
          For i = 1 To strFldName.Length
              If Mid(strFldName, i, 1).Equals(" ") Then
              Else
                  RemoveSpace = RemoveSpace & Mid(strFldName, i, 1)
              End If
          Next
      Catch ex As Exception
      End Try
  End Function

 

From Randy,

I don't even know what the hell the Try/Catch is supposed to be doing, not to mention that the programmer expanded a (typically) one-line operation to thirteen plus a number extra function calls and boolean logic.

 

Looking around, there are a lot of bad ways to do this. For instance, I found this floating around on a forum; it's how to remove every + from a string.

  char * p = s;
  while ( (p=strchr(s,'+')) != NULL )
      strcpy( p, p+1 );
For anyone that doesn't know what O(N) means, this is not it. The thread ends with someone rewriting five C functions, which he knew about because he gave his similar names.

 

I'd like to see what else you can come up with. Here's my own C++ reference implementation for how to do it in place.

  char* RemoveSpaces( char *str )
  {
      if ( NULL == str ) return NULL;

      char * to = str;

      for ( char* from = str ; '\0' != *from ; ++from )
          if ( ' ' != *from )
              *(to++) = *from;

      *to = '\0';
      return str;
  }

 

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!