将字符串和定界符拆分为数组 [英] Split string and delimiters into an array
问题描述
我有以下字符串:
top,fen,test,delay,test
我想通过以下方式将其转换为数组:
I want to convert it into an array in the following way:
{top} {,} {fen} {,} {delay} {,} {test}
推荐答案
如果实际上需要逗号作为数组的一部分,那么最简单的方法可能是执行 Replace
语句,替换每个逗号,并用一些其他字符包围,您可以将其用作定界符.无论您选择使用哪个字符,都应具有足够的唯一性,以使其不太可能出现在其余单词列表中.在这里,我将使用下划线,但是您可以使用其他任何特殊字符.
If you actually need the commas as part of the array, then probably the simplest approach is to do a Replace
statement, replacing each comma with a comma surrounded by some other character(s) you can use as a delimiter. Whatever character you opt to use should be unique enough that it is unlikely to appear in the rest of your word list. I will use an underscore, here, but you could use any other special character.
Sub test()
Dim wordlist As String
Dim arrayofWords
Dim i
wordlist = "top,fen,test,delay,test"
wordlist = Replace(wordlist, ",", "_,_")
arrayofWords = Split(wordlist, "_")
'Enclose each word in curly brackets
' omit if this part is not needed
For i = LBound(arrayofWords) To UBound(arrayofWords)
arrayofWords(i) = "{" & arrayofWords(i) & "}"
Next
End Sub
您可以使用一些时髦的双字节字符,因为在单词列表中很少会遇到这些字符,就像这样.
You could use some funky double-byte character since these would rarely if ever be encountered in your word list, like so.
Sub test()
Const oldDelimiter As String = ","
Dim splitter As String
Dim newDelimiter As String
Dim wordlist As String
Dim arrayofWords
Dim i As Long
'Create our new delimiter by concatenating a new string with the comma:
splitter = ChrW(&H25B2)
newDelimiter = splitter & oldDelimiter & splitter
'Define our word list:
wordlist = "top,fen,test,delay,test"
'Replace the comma with the new delimiter, defined above:
wordlist = Replace(wordlist, oldDelimiter, newDelimiter)
'Use SPLIT function to convert the string to an array
arrayofWords = Split(wordlist, splitter)
'Iterate the array and add curly brackets to each element
'Omit if this part is not needed
For i = LBound(arrayofWords) To UBound(arrayofWords)
arrayofWords(i) = "{" & arrayofWords(i) & "}"
Next
End Sub
这是第二种方法的结果:
Here are results from the second method:
这篇关于将字符串和定界符拆分为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!