我试图找到一种简单的方法来连接数组中的字符串 - 但前提是它们不是空的。
示例:
Dim strArr(3)
strArr(0) = "This"
strArr(1) = "is"
strArr(2) = ""
strArr(3) = "a"
strArr(4) = "test"
strResult = Join(strArr, "***")
MsgBox strResult
将生成此文字:This***is******a***test
但它应该是:This***is***a***test
因此应忽略空字符串。
答案 0 :(得分:4)
Option Explicit
Dim aStrArray
aStrArray = Array("", "", "This", "", "", "is", "", "", "", "a", "test", "", "")
Dim strResult
strResult = MyJoin(aStrArray, "***")
WScript.Echo strResult
Function MyJoin( inputArray, inputDelimiter )
Dim delimiter
delimiter = Chr(1) & Chr(2)
With New RegExp
.Pattern = "^(?:" & delimiter & ")+" & _
"|(?:" & delimiter & ")+$" & _
"|(?:" & delimiter & ")+(" & delimiter & ")"
.Global = True
MyJoin = Replace(.Replace(Join(inputArray, delimiter), "$1"), delimiter, inputDelimiter)
End With
End Function
您只能使用一个分隔符替换多次出现的分隔符。
在示例代码中的函数中:
答案 1 :(得分:1)
下一个代码段可以帮助(甚至ReDim
strArr
}:
option explicit
Dim strArr, strResult, strJoinString
ReDim strArr(4)
strArr(0) = "This"
strArr(1) = "is"
strArr(2) = ""
strArr(3) = "a"
strArr(4) = "test"
strJoinString = "€€€"
strResult = Join(strArr, strJoinString)
Do While Instr(1, strResult, strJoinString & strJoinString, vbBinaryCompare) > 0
strResult = Replace( strResult, strJoinString & strJoinString, strJoinString)
Loop
strArr = Split(strResult, strJoinString)
strResult = Join(strArr, "***")
MsgBox strResult & vbNewLine & Join(strArr, "-")
确保strJoinString
与任何数组元素都不匹配!
答案 2 :(得分:0)
一种方法是将所有非空字段复制到字典中,然后加入该字典的值:
Set d = CreateObject("Scripting.Dictionary")
For i = 0 To UBound(strArr)
If strArr(i) <> "" Then d.Add i, strArr(i)
Next
WScript.Echo Join(d.Items, "***")