我正在尝试编写一个函数,该函数至少需要两个,最多六个字符串,这些字符串应该连接成一个逗号分隔的字符串。 以下是我最近的尝试,但尾随的“,”并没有删除?
Private Function GetConcatenatedStrings(str1 As String, str2 As String, Optional str3 As String = "",
Optional str4 As String = "", Optional str5 As String = "", Optional str6 As String = "") As String
Dim result = String.Empty
result =
IIf(Not String.IsNullOrWhiteSpace(str1), str1 & ", ", "") &
IIf(Not String.IsNullOrWhiteSpace(str2), str2 & ", ", "") &
IIf(Not String.IsNullOrWhiteSpace(str3), str3 & ", ", "") &
IIf(Not String.IsNullOrWhiteSpace(str4), str4 & ", ", "") &
IIf(Not String.IsNullOrWhiteSpace(str5), str5 & ", ", "") &
IIf(Not String.IsNullOrWhiteSpace(str6), str6, "")
result = result.Trim(",")
result = result.Trim("")
Return result
End Function
电位
Private Function GetConcatenatedStrings(Optional str1 As String = "", Optional str2 As String = "",
Optional str3 As String = "", Optional str4 As String = "",
Optional str5 As String = "", Optional str6 As String = "") As String
Dim result = String.Empty
Dim Strings() As String = {str1, str2, str3, str4, str5, str6}
For Each value In Strings
If Not String.IsNullOrWhiteSpace(value) Then result &= ", " + value
Next
If Not String.IsNullOrWhiteSpace(result) Then
result = result.Substring(1)
End If
Return result
End Function
Private Function GetConcatenatedStrings(Optional str1 As String = "", Optional str2 As String = "",
Optional str3 As String = "", Optional str4 As String = "",
Optional str5 As String = "", Optional str6 As String = "") As String
Dim result = String.Empty
Dim list As New List(Of String)
list.Add(str1)
list.Add(str2)
list.Add(str3)
list.Add(str4)
list.Add(str5)
list.Add(str6)
list.RemoveAll(Function(str) String.IsNullOrWhiteSpace(str))
result = String.Join(", ", list)
Return result
End Function
答案 0 :(得分:2)
归结为单线。试试这个:
Private Function GetConcatenatedStrings(ByVal ParamArray items() As String) As String
Return String.Join(",", items.Where(Function(s) Not String.IsNullOrWhiteSpace(s)))
End Function
这与您当前的代码有两点不同:
第二项比bug更具特色。如果你关心第一个项目,你可以调整函数签名,以便在两个" normal"之后包含ParamArray。字符串参数,然后更新items
列表。我更喜欢简洁。
像这样调用函数:
Dim result As String = GetConcatenatedStrings("any", "number", "of", "strings", "you", "want")
答案 1 :(得分:1)
你有一个尾随","有空间 - 不只是","
为了获得更大的灵活性,请尝试一下......
Public Function GetConcatenatedStrings(ByVal ParamArray strings() As String) As String
Dim result As String = String.Empty
For Each value In strings
If Not String.IsNullOrWhiteSpace(value) Then result &= "," + value
Next
Return result.Substring(1)
End Function