.NET Array Dictionary List String Sub ArrayList Cast Class Console Dates DataTable DateTime Enum File For Format If IndexOf Lambda LINQ Nothing Parse Process Property Regex Replace Select Sort Split StringBuilder SubstringReplace. This changes the contents of a String. It makes all instances of one substring become another substring. The Replace function on String is often useful.
Tip:All instances of the first parameter's string data are replaced with the second parameter's string data.
Nothing:You can use an empty string literal or the Nothing literal to indicate an empty string.
Here:In this example, we replace the first word parameter with the second word parameter.
Based on: .NET 4.5 VB.NET program that uses Replace Module Module1 Sub Main() ' Assign string to literal. Dim value1 As String = "XXpagitica" Console.WriteLine(value1) ' Replace substring with another substring. Dim value2 As String = value1.Replace("XX", "Areo") Console.WriteLine(value2) End Sub End Module Output XXpagitica Areopagitica
Tip:This behavior is useful when dealing with common string replacements in programs.
But:If you do not understand this behavior you may end up writing inefficient code that has unneeded loops.
Here:The string containing the characters "Net" is replaced with the characters "Bottle". These substrings are case-sensitive.
VB.NET program that uses Replace on instances Module Module1 Sub Main() ' Assign string to literal constant. Dim value1 As String = "Dot Net Perls is about Dot Net." Console.WriteLine(value1) ' Replace every instance of the string. Dim value2 As String = value1.Replace("Net", "Bottle") Console.WriteLine(value2) End Sub End Module Output Dot Net Perls is about Dot Net. Dot Bottle Perls is about Dot Bottle.
However:The StringBuilder class implements optimizations that can improve memory usage and speed when doing many replacements.
VB.NET program that uses StringBuilder Replace Imports System.Text Module Module1 Sub Main() ' Create new StringBuilder and initialize it. Dim builder As New StringBuilder("This is an example.") Console.WriteLine(builder) ' Replace string in StringBuilder. builder.Replace("This", "Here") Console.WriteLine(builder) ' Insert into StringBuilder. builder.Insert(0, "Sentence: ") Console.WriteLine(builder) End Sub End Module Output This is an example. Here is an example. Sentence: Here is an example.
Tip:If you have many replacements to perform, using StringBuilder will likely perform better.
Tip:Often we can convert a string into a StringBuilder, and then use the Replace, Append and Insert methods on that StringBuilder.
Then:We can convert the StringBuilder back into a string with the ToString method.
Tip:Regular expressions allow you to do much more complex replacements with less code.
However:Simple replacements are faster to do in the String or StringBuilder classes. The regular expression parser has overhead.