Pancos
Pancos

Reputation: 21

Visual Basic loop removing the last character

I have just started to learn Visual Basic and I am having trouble with a loop. What I want it to do is print out the string "ABCDEFG" into a list box then remove the last character and print it out until only "A" is left. This is the code I am using:

Dim abc As String = "ABCDEFG"

For i = 0 To 5
    abc.Substring(0, abc.Length - 1)
    lstabc.Items.Add(abc)
Next i

The desired result would look like this but all i get is lines of "ABCDEFG"

ABCDEFG
ABCDEF
ABCDE
ABCD
ABC
AB
A

Upvotes: 0

Views: 306

Answers (2)

Sonal Borkar
Sonal Borkar

Reputation: 561

String in c#, vb.net are non mutable. So you need to store the result in another variable and print that variable.

  Dim substr As String 
  substr = abc.Substring(0, abc.Length - i)
  lstabc.Items.Add(substr)

Upvotes: 0

hynsey
hynsey

Reputation: 135

You're never assigning anything different to abc, so it's always adding the full string. Also, you are not specifying a different length to substring. Try this.

Dim abc As String = "ABCDEFG"
Dim abc_alt as String
For i = 0 To abc.Length - 1
    abc_alt = abc.Substring(0, abc.Length - i)
    lstabc.Items.Add(abc_alt)
Next i

Upvotes: 3

Related Questions