Recipe 5.31. Reversing a String


You want to reverse, or mirror image, the order of the characters in a string.


Use the StrReverse() function.


The StrReverse() function makes reversing a string simple:

 Dim quote As String = "The important thing is not to " & _    "stop questioning. --Albert Einstein" Dim reversed As String = StrReverse(quote) MsgBox(reversed) 

Figure 5-35 shows the reversed string as displayed in the message box.

Figure 5-35. The sample string reversed

Another way to reverse a string is to process the characters yourself. This sample code scans through the string in reverse order and appends each found character to a new StringBuilder instance:

 Dim quote As String = "The important thing is not to " & _    "stop questioning. --Albert Einstein" Dim counter As Integer Dim result As New System.Text.StringBuilder(quote.Length) For counter = quote.Length - 1 To 0 Step -1    result.Append(quote.Chars(counter)) Next counter Dim reversed As String = result.ToString() MsgBox(reversed) 

The overloaded constructor for the StringBuilder accepts an optional parameter defining the capacity the StringBuilder should use for its internal character buffer. Since we know the reversed string will be the same length as the original, the capacity can be set to exactly the amount needed. This prevents the StringBuilder from having to double its capacity when it runs low on space while appending characters (see Recipe 5.1). Using the Chars property of the string to grab characters and setting the initial capacity of the StringBuilder in this way ensures that the character bytes are transferred in memory just once in a tight, efficient loop.

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: