String ReverseReverse the characters in Strings using ToCharArray and Array.Reverse.
This page was last reviewed on Sep 13, 2023.
Reverse String. A String contains individual characters. The order of these characters can be reversed. But we cannot change a string directly.
Implementation notes. In VB.NET we reverse a string using the ToCharArray function. We then use the Array.Reverse Sub, and finally the String constructor.
An example. In Reverse() we store the value returned by ToCharArray in a local variable. Next pass that variable to the Array.Reverse subroutine.
Info Reverse internally rearranges the characters in the array to be in the opposite order.
Finally You must invoke the 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 Module
drib tac
Interviews. Readers have commented that in interview questions, the classic question of writing a method to reverse a string often have some constraints.
Info For example, you might be required not to call methods such as Array.Reverse.
However Even with these constraints, you would likely need to use the String constructor or possibly ToCharArray.
String ToCharArray
Detail With this program, we could call ToCharArray on the "test" string and the program would compile correctly.
Module Program Sub Main() Array.Reverse("test") End Sub End Module
Error BC30311 Value of type 'String' cannot be converted to 'Array'.
A summary. Strings in VB.NET cannot be manipulated directly. They are immutable. You must convert them to character arrays with the ToCharArray function.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2024 Sam Allen.