vba 将字符串拆分为字符数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13195583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split string into array of characters?
提问by mezamorphic
How is it possible to split a VBA string into an array of characters?
如何将 VBA 字符串拆分为字符数组?
I tried Split(my_string, "")
but this didn't work.
我试过了,Split(my_string, "")
但这没有用。
回答by Alex K.
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;
如果您保证只使用 ansi 字符,则可以;
Dim buff() As String
buff = Split(StrConv(my_string, vbUnicode), Chr$(0))
ReDim Preserve buff(UBound(buff) - 1)
回答by Charles Williams
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
您可以将字符串分配给一个字节数组(反过来也是可能的)。结果是每个字符有 2 个数字,因此 Xmas 转换为包含 {88,0,109,0,97,0,115,0} 的字节数组,
或者您可以使用 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
这会给你 {88,109,97,115} 但在这种情况下,你不能将字节数组分配回字符串。
您可以使用 Chr() 函数将字节数组中的数字转换回字符
回答by Daniel
Here's another way to do it in VBA.
这是在 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
回答by q335r49
According to this code golfing solution by Gaffi, the following works:
根据Gaffi 的代码高尔夫解决方案,以下工作:
a = Split(StrConv(s, 64), Chr(0))
回答by user3738926
the problem is that there is no built in method (or at least none of us could find one) to do this in vb. However, there is one to split a string on the spaces, so I just rebuild the string and added in spaces....
问题是在 vb 中没有内置方法(或者至少我们没有人能找到)来做到这一点。但是,有一个可以在空格上拆分字符串,所以我只是重建字符串并添加空格....
Private Function characterArray(ByVal my_string As String) As String()
'create a temporary string to store a new string of the same characters with spaces
Dim tempString As String = ""
'cycle through the characters and rebuild my_string as a string with spaces
'and assign the result to tempString.
For Each c In my_string
tempString &= c & " "
Next
'return return tempString as a character array.
Return tempString.Split()
End Function