How to: Convert a String to an Array of Characters in Visual Basic
Sometimes it is useful to have data about the characters in your string and the positions of those characters within your string, such as when you are parsing a string. This example shows how you can get an array of the characters in a string by calling the string's ToCharArray method.
Example 1
This example demonstrates how to split a string into a Char
array, and how to split a string into a String
array of its Unicode text characters. The reason for this distinction is that Unicode text characters can be composed of two or more Char
characters (such as a surrogate pair or a combining character sequence). For more information, see TextElementEnumerator and The Unicode Standard.
Dim testString1 As String = "ABC"
' Create an array containing "A", "B", and "C".
Dim charArray() As Char = testString1.ToCharArray
Example 2
It is more difficult to split a string into its Unicode text characters, but this is necessary if you need information about the visual representation of a string. This example uses the SubstringByTextElements method to get information about the Unicode text characters that make up a string.
' This string is made up of a surrogate pair (high surrogate
' U+D800 and low surrogate U+DC00) and a combining character
' sequence (the letter "a" with the combining grave accent).
Dim testString2 As String = ChrW(&HD800) & ChrW(&HDC00) & "a" & ChrW(&H300)
' Create and initialize a StringInfo object for the string.
Dim si As New System.Globalization.StringInfo(testString2)
' Create and populate the array.
Dim unicodeTestArray(si.LengthInTextElements - 1) As String
For i As Integer = 0 To si.LengthInTextElements - 1
unicodeTestArray(i) = si.SubstringByTextElements(i, 1)
Next