如何将字符串和分隔符拆分为数组

时间:2014-08-14 02:21:27

标签: excel-vba vba excel

我有以下字符串:

top,fen,test,delay,test

我想通过以下方式将其转换为数组:

{top}{,}{fen}{,}{delay}{,}{test}

3 个答案:

答案 0 :(得分:3)

如果你真的需要逗号作为数组的一部分,那么最简单的方法可能就是做一个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

以下是第二种方法的结果:

enter image description here

答案 1 :(得分:0)

尝试这样的事情:

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.com/en-us/library/6x627e5f%28v=vs.90%29.aspx

UBound:http://msdn.microsoft.com/en-us/library/95b8f22f%28v=vs.90%29.aspx

Redim:http://msdn.microsoft.com/en-us/library/w8k3cys2.aspx

答案 2 :(得分:0)

这是真正的简短解决方案:

Function StringToCurlyArray(s As String) As String()

    StringToCurlyArray = Split("{" & Replace(s, ",", "}|{,}|{") & "}", "|")

End Function

将逗号分隔的字符串传递给该字符串,然后您将获得一系列支持卷曲的字符串,包括逗号。