Recipe 5.16. Replacing Substrings


You need to find and replace all occurrences of a substring in a larger string.


Use the String object's Replace() method.


The following example replaces all occurrences of lowercase "ing" with uppercase "ING" in a sample string:

 Dim quote As String = "The important thing is not to " & _    "stop questioning. --Albert Einstein" Dim result As String = quote.Replace("ing", "ING") MsgBox(result) 

Figure 5-14 shows the results, where two occurrences were found and replaced.

Figure 5-14. Replacing multiple substrings

In this example, the substrings are replaced with a new string of the same length, but the replacement string can be of differing length. In fact, a useful technique is to make a replacement with a zero-length string, effectively deleting all occurrences of a given substring. For example, the following code, applied to the original string, results in the shortened string displayed in Figure 5-15:

 result = Quote.Replace("not to stop ", "") 

Figure 5-15. Zapping substrings by replacing them with an empty string

See Also

Recipe 5.21 shows how to remove characters from the start and end of a string.

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: