Search code examples
vb.netchararray

How to remove an element from a char array in VB.NET?


is there any way to remove the element in char array I converted from a String?

Dim myString As String = "Hello"
Dim charArray As Char() = myString.ToCharArray

Your help would be much appreciated.. Thanks


Solution

  • Arrays are fixed-length in .NET. You can set an element to Nothing but you cannot remove that element. You can use a collection instead of an array and then you can add, insert and remove items at will, but your example isn't necessarily the best case for that sort of thing, e.g.

    Dim str = "Hello"
    Dim chars = New List(Of Char)(str)
    

    You can then call Remove or RemoveAt on that List to remove a Char. You can then create a new String if desired, e.g.

    chars.RemoveAt(2)
    str = New String(chars.ToArray())
    
    Console.WriteLine(str)
    

    That will display "Helo".