我有以下字符串。
top,fen,test,delay,test
我想用下面的方法把它转换成一个数组:
{top}{,}{fen}{,}{delay}{,}{test}
如果你真的需要逗号作为数组的一部分,那么可能最简单的方法是做一个 Replace
语句,用一个逗号代替每个逗号,逗号周围用一些其他字符作为分隔符。无论您选择使用什么字符,都应该足够独特,以至于它不可能出现在您的单词列表的其余部分。 我将在这里使用下划线,但你可以使用任何其他特殊字符。
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
你可以使用一些时髦的双字节字符,因为这些字符在你的单词列表中很少会出现,比如这样。
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
这里是第二种方法的结果。
试试像这样:
WordsList = Split("top,fen,test,delay,test", ",")
Result = ""
Count = UBound(WordsList)
For i = 0 To Count
Result = Result & "{" & WordsList(i) & "}"
if i < Count then Result = Result & "{,}"
Next i
在一个数组中看起来会是这样的。
WordsList = Split("top,fen,test,delay,test", ",")
Dim Result()
Count = (UBound(WordsList)*2) - 1
Redim Result(Count)
j = 0
For i = 0 To UBound(WordsList)
Result(j) = WordsList(i)
j = j + 1
if j < Count then Result(j) = ","
j = j + 1
Next i
拆分。http:/msdn.microsoft.comen-uslibrary6x627e5f%28v=vs.90%29.aspx。
ubound.comen-uslibrary95b8f22f%28v=vs.90%29.aspx http:/msdn.microsoft.comen-uslibrary95b8f22f%28v=vs.90%29.aspx。
这里有一个 真的 简单的解决方案。
Function StringToCurlyArray(s As String) As String()
StringToCurlyArray = Split("{" & Replace(s, ",", "}|{,}|{") & "}", "|")
End Function
把你的以逗号分隔的字符串传给它 你会得到一个包括逗号在内的大括号字符串数组出来