Microsoft Visual Studio – How to remove last character(s) from a string

Let’s say I am concatenating a string with values from a collection. Every time I add a value, I want to append with a comma (,) and a space to separate. I don’t know at run time how many objects are in my collection, so when I am done, I need to remove the last comma (,) and space. The following code shows how the string is  built, what it may look like when completed, and how to remove the last two characters – comma (,) and a space.

Dim mHobbies As String = String.Empty
Dim pObj as Object
For each pObj in myHobbyCollection
 With pObj
      mHobbies= mHobbies & .hobby & ", "
 End With
Next

mHobbies may contain the following:

Music, Reading, Swimming, Kite Flying,  

The following code will remove the last two characters:

mHobbies = mHobbies.Remove(mHobbies.Length – 2)

mHobbies will now look like this:

Music, Reading, Swimming, Kite Flying

Leave a Reply