Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into array of characters?

Tags:

string

char

vba

How is it possible to split a VBA string into an array of characters?

I tried Split(my_string, "") but this didn't work.

like image 380
mezamorphic Avatar asked Nov 02 '12 12:11

mezamorphic


People also ask

How do you split a string into an array of letters?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you split a string into an array of characters Python?

To convert String to array in Python, use String. split() method. The String . split() method splits the String from the delimiter and returns the splitter elements as individual list items.

How do you split a string into characters?

Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.


4 Answers

Safest & simplest is to just loop;

Dim buff() As String ReDim buff(Len(my_string) - 1) For i = 1 To Len(my_string)     buff(i - 1) = Mid$(my_string, i, 1) Next 

If your guaranteed to use ansi characters only you can;

Dim buff() As String buff = Split(StrConv(my_string, vbUnicode), Chr$(0)) ReDim Preserve buff(UBound(buff) - 1) 
like image 124
Alex K. Avatar answered Oct 03 '22 09:10

Alex K.


You can just assign the string to a byte array (the reverse is also possible). The result is 2 numbers for each character, so Xmas converts to a byte array containing {88,0,109,0,97,0,115,0}
or you can use StrConv

Dim bytes() as Byte
bytes = StrConv("Xmas", vbFromUnicode)

which will give you {88,109,97,115} but in that case you cannot assign the byte array back to a string.
You can convert the numbers in the byte array back to characters using the Chr() function

like image 42
Charles Williams Avatar answered Oct 03 '22 08:10

Charles Williams


Here's another way to do it in VBA.

Function ConvertToArray(ByVal value As String)
    value = StrConv(value, vbUnicode)
    ConvertToArray = Split(Left(value, Len(value) - 1), vbNullChar)
End Function
Sub example()
    Dim originalString As String
    originalString = "hi there"
    Dim myArray() As String
    myArray = ConvertToArray(originalString)
End Sub
like image 45
Daniel Avatar answered Oct 03 '22 09:10

Daniel


According to this code golfing solution by Gaffi, the following works:

a = Split(StrConv(s, 64), Chr(0))
like image 45
q335r49 Avatar answered Oct 03 '22 08:10

q335r49