You need to work with individual characters in a string efficiently, changing them in place in memory if possible.
Sample code folder: Chapter 05\StringsAndCharArrays
Use CType() to convert the string to an array of characters, modify characters throughout the array, and then directly convert the character array back to a string:
Dim quote As String = "The important thing is not to " & _ "stop questioning. --Albert Einstein" Dim charArray() As Char = CType(quote, Char()) charArray(46) = "!"c Dim result As String = New String(charArray) MsgBox(result)
In this example, the string is converted to a character array using the versatile CType() type-conversion function. In this form, it's easy to make a change such as replacing the period at index 46 with an exclamation point. The array is then recombined into a string by passing it to the overloaded version of the String constructor that takes an array of characters to initialize the new string. Figure 5-8 shows the displayed string result, now showing an exclamation point instead of a period.
Figure 5-8. Converting a string to an array of characters enables easy modification of individual characters in that string
There is another way to access individual characters in a string, but it's read-only, so you can't use the technique to modify the string:
All strings have a Chars() property that lets you access an indexed character from the string with minimal overhead. The index is zero-based, so Chars(46) returns the 47th character.
Recipe 5.12 also examines working with individual characters within a larger string.