Reversing a String - VB.NET
If you need to reverse the order of characters in a string, here is a simple way to do it:
Dim OurString As String = "thisistext" Dim CharacterArray() As Char = OurString.ToCharArray() Array.Reverse(CharacterArray) OurString = CharacterArray ' Result: "txetsisiht"
Firstly we assign “thisistext” to OurString. We then create an array, CharacterArray, of type Char. This means each item of the array will contain a single character value.
We then populate CharacterArray with the contents of OurString with the ToCharArray() method. This takes each character in OurString and assigns it to it’s own item in CharacterArray.
Then we call the Array.Reverse function, passing to it CharacterArray. This function takes an array as a parameter and reverses the order of the items.
We then re-assign OurString to equal the now reveresed values of CharacterArray!
This is probably not the most efficient way to reverse a string but it is simple and wrapped up in a function it is quick and easy. If anyone has a more efficient way I’d be interested in hearing about it.