Visual Basic String Replace Method

In visual basic, the string Replace method is useful to replace the specified string or a character in all occurrence of given string.

 

The Replace method in visual basic will return a new string after replacing all the occurrences of specified string or a character.

 

Following is the pictorial representation of string Replace method in visual basic programming language.

 

Visual Basic String Replace Method Representation Diagram

 

If you observe the above diagram, we are replacing the “Hi” word in the given string “Hi Guest Hi” with “Welcome” using Replace method. Once the replacement is done, the Replace method will return a new string like “Welcome Guest Welcome”.

Visual Basic String Replace Method Example

Following is the example of using Replace() method to replace a particular part of string or a character visual basic programming language.

 

Module Module1

    Sub Main()

        Dim msg As String = "Hi Guest Hi"

        Dim nmsg As String = msg.Replace("Hi", "Welcome")

        Console.WriteLine("Old: {0}", msg)

        Console.WriteLine("New: {0}", nmsg)

        Dim x As String = "aaaaa"

        Dim nx As String = x.Replace("a", "b").Replace("b", "c")

        Console.WriteLine("Old: {0}", x)

        Console.WriteLine("New: {0}", nx)

        Dim y As String = "1 2 3 4 5 6 7"

        Dim ny As String = y.Replace(" ", ",")

        Console.WriteLine("Old: {0}", y)

        Console.WriteLine("New: {0}", ny)

        Console.WriteLine("Press Enter Key to Exit..")

        Console.ReadLine()

    End Sub

End Module

If you observe the above example, we used a Replace() method to replace the particular part of string or a character in the given string and returning a new string.

 

When we execute the above visual basic program, we will get the result like as shown below.

 

Visual Basic String Replace Method Example Result

 

This is how we can use Replace() method to replace a particular part of string or a character in visual basic programming language.

Topics Covered