VB.NET Add, Remove and Replace Strings

This code snippet shows how to add, remove and replace strings in VB.NET.
  • 8606

The Insert method inserts a specified string at a specified index position in an instance. For example, the following source code inserts "bbb" after second character in str1 and the result string is "pbbbpp".

    Dim str1 As String
    Dim
StrRes As String
    str1 = "ppp"
    strRes = str1.Insert(2, "bbb")
    Console.WriteLine(StrRes.ToString())

The Remove method deletes a specified number of characters from a specified position in a string. This method returns result as a string. For example, the following code removes three characters from index 3.

    Dim s As String = "123abc000"
    Console.WriteLine(s.Remove(3, 3))

The Replace method replaces all occurrences of a specified character in a string. For example, the following source code replaces all p character instances of str1 with character l and returns string "lll".

    Dim str1 As String = "ppp"
    Dim repStr As String = str1.Replace("p"c, "l"c)
    Console.WriteLine("Replaced string:" & repStr.ToString())

The Split method separates strings by a specified set of characters and places these strings into an array of strings. For example, the following source code splits strArray based on ',' and stores all separated strings in an array.

    Dim str1 As String = "ppp"
    Dim str2 As String = "ccc"
    Dim str3 As String = "kkk"
    Dim strAll3 As String = str1 & ", " & str2 & ", " & str3
    Dim strArray As String() = strAll3.Split(","c)
    For Each itm As String In strArray
        Console.Write(itm.ToString())
    Next

Conclusion

Hope this article would have helped you in understanding add, remove and replace strings in VB.NET.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.