gpt4 book ai didi

.net - 逗号 "izing"项目列表

转载 作者:可可西里 更新时间:2023-11-01 07:59:41 25 4
gpt4 key购买 nike

给定一个字符串列表,将这些字符串连接成逗号分隔且末尾没有逗号的列表的最佳方法是什么。 (VB.NET 或 C#)(使用 StringBuilder 或 String Concat。)

Dim strResult As String = ""
Dim lstItems As New List(Of String)
lstItems.Add("Hello")
lstItems.Add("World")
For Each strItem As String In lstItems
If strResult.Length > 0 Then
strResult = strResult & ", "
End If
strResult = strResult & strItem
Next
MessageBox.Show(strResult)

最佳答案

Dim Result As String
Dim Items As New List(Of String)
Items.Add("Hello")
Items.Add("World")

Result = String.Join(",", Items)
MessageBox.Show(Result)

如果您真的担心空字符串,请使用此连接函数:

Function Join(ByVal delimiter As String, ByVal items As IEnumerable(Of String), Optional ByVal IgnoreEmptyEntries As Boolean = True) As String
Dim delim As String = ""
Dim result As New Text.StringBuilder("")

For Each item As String In items
If Not IgnoreEmptyEntries OrElse Not String.IsNullOrEmpty(item) Then
result.Append(delim).Append(item)
delim = delimiter
End If
Next
Return result.ToString()
End Function

上面真的很老了。今天,我会像这样清除空字符串:

Dim Result As String = String.Join("," Items.Where(Function(i) Not String.IsNullOrWhitespace(i)))

关于.net - 逗号 "izing"项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/368551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com