Nick
Nick

Reputation: 39

I wrote a code which reverses a string (and it does), but I don't think it's the clean/right way to do it

I wanted to get familiar with the built-in functions of VB, specifically, the len() function. However, I think this may not be the right way to concatenate a string with a char.

Also, it may interest you that the error list says,

"Warning 1 Variable 'reverse' is used before it has been assigned a value. A null reference exception could result at runtime."

I executed the program but it ran fine. Here's the code:

Sub Main()
    Dim a As String
    Console.WriteLine("Enter the value of the string you want to reverse: ")
    a = Console.ReadLine()
    Dim reverse As String
    Dim temp As Char
    Dim str As Integer
    str = Len(a)
    For x = str To 1 Step -1
        temp = Mid(a, x)
        reverse = reverse + temp
    Next x
    Console.WriteLine(reverse)
    Console.ReadKey()
End Sub

I'm still learning this language and so far it's been really fun to make small programs and stuff.

Upvotes: 2

Views: 359

Answers (2)

sujith karivelil
sujith karivelil

Reputation: 29006

You are getting the warning

"Warning 1 Variable 'reverse' is used before it has been assigned a value. A null reference exception could result at runtime."

Because String variable reverse is not yet initialized. Compiler will consider the scenario that For is not executing in such situation the reverse can be null. you can get out of the warning by assigning an empty value to the string: ie.,

 Dim reverse As String=String.Empty

You can do the functionality in the following ways too:

 Dim inputStr As String = String.Empty
 Console.WriteLine("Enter the value of the string you want to reverse: ")
 inputStr = Console.ReadLine()
 Dim reverse As String = String.Join("", inputStr.AsEnumerable().Reverse)
 Console.WriteLine(reverse)
 Console.ReadKey()

OR

  Dim reverse As String = String.Join("", inputStr.ToCharArray().Reverse)

Upvotes: 1

Rob
Rob

Reputation: 3853

Dim TestString As String = "ABCDEFG" 
Dim revString As String = StrReverse(TestString)

ref: https://msdn.microsoft.com/en-us/library/e462ax87(v=vs.90).aspx

Upvotes: 1

Related Questions