Recipe 5.10. Converting Strings to and from Character Arrays


Problem

You need to work with individual characters in a string efficiently, changing them in place in memory if possible.

Solution

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) 

Discussion

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:

 MsgBox(someString.  Chars(46)) 

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.

See Also

Recipe 5.12 also examines working with individual characters within a larger 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

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net