Converting a string to a char array
Solution 1
Every string is an implicit char-array. So you can get the 3rd char by:
Dim char3 = str(2)
Edit: Just for the sake of completeness. You can also use String.ToCharArray
to convert the string instance to a new char-array
instance. The core benefit of using ToCharArray
is that the char-array you receive is mutable, meaning you can actually change each individual character.
Note that you could also use LINQ
. If you for example want the first three characters of a String:
Dim firstThree As Char() = str.Take(3).ToArray()
Solution 2
dim chars as Char() = str.ToCharArray()
Solution 3
Try:
Dim str As String = "code"
' Use For Each loop on string.
For Each element As Char In str
Console.WriteLine(element)
Solution 4
Referencing @AlexeiLevenkov,
You can use String.ToCharArray to convert it to array of characters, or use ToArray if you like LINQ more:
Dim delimStr As String = " ,.:" Dim delimiter As Char() = delimStr.ToCharArray() "foo".ToArray()
(I added the above alternative as the duplicate question will be soon closed; it is worth keeping the LINQ alternative.)
Solution 5
I did some benchmarking and ToCharArray is approximately 30 times faster than LINQ's ToArray.
Isuru
Started out as a C# developer. Turned to iOS in 2012. Currently learning SwiftUI. Loves fiddling with APIs. Interested in UI/UX. Want to try fiddling with IoT. Blog | LinkedIn
Updated on July 09, 2022Comments
-
Isuru almost 2 years
Let's say I have a string like this.
Dim str As String = "code"
I need to break this string down to an array of characters like this,
{"c", "o", "d", "e"}
How can I do this?
-
Isuru about 12 yearsThat's all I wanted to know. :D I got it now. Thank you.
-
Isuru about 12 yearsTried this now and it works too. :) Always good to know extra ways. Thank you.