Posts VB.NET string method to handle escape sequences.

VB.NET string method to handle escape sequences.

After reading some comments by Alex Hoffman, I've put together a quick and dirty function that will do some of what he is complaining that VB.NET isn't capable of doing.  I've also made it so that this particular function doesn't require a reference to the VisualBasic namespace since he was complaining about that too.  I like my VisualBasic namespace... it's my friend :-)

Here's the quick and dirty escape sequence string function to assist converting code from C# to VB.NET.

Function EscapeString(ByVal s As String) As String
  '\' - Single quote 0x0027
If s.IndexOf("\'") > 0 Then
s = s.Replace("\'", "'")
End If
'\" - Double quote 0x0022
If s.IndexOf("\" & Chr(&H22)) Then
s = s.Replace("\" & Chr(&H22), Chr(&H22))
  End If
  '\0 - Null 0x0000
  If s.IndexOf("\0") Then
    s = s.Replace("\0", Chr(&H0))
  End If
  '\a - Alert 0x0007
  If s.IndexOf("\a") > 0 Then
    s = s.Replace("\a", Chr(&H7))
  End If
  '\b - Backspace 0x0008
  If s.IndexOf("\b") > 0 Then
    s = s.Replace("\b", Chr(&H8))
  End If
  '\f - Form feed 0x000C
  If s.IndexOf("\f") > 0 Then
    s = s.Replace("\f", Chr(&HC))
  End If
  '\n - New line 0x000A
  If s.IndexOf("\n") > 0 Then
    s = s.Replace("\n", Environment.NewLine)
    'or s = s.Replace("\n", vbLf)
    'or s = s.Replace("\n", Chr(10))
    'or s = s.Replace("\n", Chr(&HA))
  End If
  '\r - Carriage return 0x000D
  If s.IndexOf("\r") > 0 Then
    s = s.Replace("\r", Chr(&HD)
    'or s = s.Replace("\n", Chr(13))
    'or s = s.Replace("\n", vbCR)
  End If
  '\t - Horizontal tab 0x0009
  If s.IndexOf("\v") Then
    s = s.Replace("\v", Chr(&H9))
  End If
  '\v - Vertical tab 0x000B
  If s.IndexOf("\v") Then
    s = s.Replace("\v", Chr(&HB))
  End If
  '\\ - Backslash 0x005C
  If s.IndexOf("\\") Then
    s = s.Replace("\\", Chr(&H5C))
  End If
  Return s
End Function

I'm Checking the IndexOf so that we don't create any unncessary string copies during the replacement process.  This helps a bit on the performance and memory manager.

Again, this is quick and dirty; so there could be some issue under some specific escape character combinations.  Anyone have a better suggestion for doing this?  First though that comes to my mind would be possibly using regular expressions.

This post is licensed under CC BY 4.0 by the author.