Visual Basic Programming Code Examples
Visual Basic > Strings Code Examples
Reverse a string using a byte array
Reverse a string using a byte array
The following function demonstrates how to effeciently reverse a string using a byte array.
'Purpose : Reverses a string
'Inputs : sValue The string to reverse.
'Outputs : The reversed of the input string variable sValue.
'Notes : The data is copied into a byte array for speed, then
Public Function StringReverse(sValue As String) As String
Dim lThisByte As Long, lUBound As Long
Dim abyteOriginal() As Byte, abyteReversed() As Byte
If Len(sValue) Then
'Copy string into byte array
abyteOriginal = sValue
lUBound = UBound(abyteOriginal)
'Size output array
ReDim abyteReversed(lUBound)
'Loop over array swaping Unicode blocks over
For lThisByte = 0 To lUBound Step 2
abyteReversed(lThisByte) = abyteOriginal(lUBound - lThisByte - 1)
abyteReversed(lThisByte + 1) = abyteOriginal(lUBound - lThisByte)
Next
'Return result
StringReverse = abyteReversed
End If
End Function