Reverse
String
A String
contains individual characters. The order of these characters can be reversed. But we cannot change a string
directly.
In VB.NET we reverse a string
using the ToCharArray
function. We then use the Array.Reverse
Sub
, and finally the String
constructor.
In Reverse()
we store the value returned by ToCharArray
in a local variable. Next pass that variable to the Array.Reverse
subroutine.
Reverse
internally rearranges the characters in the array to be in the opposite order.String
constructor. This converts the reversed character array back into a string
.Module Module1 Sub Main() ' Test. Console.WriteLine(Reverse("bird")) Console.WriteLine(Reverse("cat")) End Sub ''' <summary> ''' Reverse input string. ''' </summary> Function Reverse(ByVal value As String) As String ' Convert to char array. Dim arr() As Char = value.ToCharArray() ' Use Array.Reverse function. Array.Reverse(arr) ' Construct new string. Return New String(arr) End Function End Moduledrib tac
Readers have commented that in interview questions, the classic question of writing a method to reverse a string
often have some constraints.
Array.Reverse
.String
constructor or possibly ToCharArray
.ToCharArray
on the "test" string
and the program would compile correctly.Module Program Sub Main() Array.Reverse("test") End Sub End ModuleError BC30311 Value of type 'String' cannot be converted to 'Array'.
Strings in VB.NET cannot be manipulated directly. They are immutable. You must convert them to character arrays with the ToCharArray
function.