In visual basic, the string Replace method is useful to replace the specified string or a character in all occurrences of a given string.
The Replace method in visual basic will return a new string after replacing all the occurrences of a specified string or a character.
Following is the pictorial representation of the string Replace method in a visual basic programming language.
If you observe the above diagram, we are replacing the “Hi” word in the given string “Hi Guest Hi” with “Welcome” using the Replace method. Once the replacement is done, the Replace method will return a new string like “Welcome Guest Welcome”.
Following is the example of using a 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 a string or a character in the given string and returns a new string.
When we execute the above visual basic program, we will get the result as shown below.
This is how we can use Replace() method to replace a particular part of a string or a character in a visual basic programming language.