这是我的代码:
With ad.Tables(2)
For i As Integer = 0 To .Rows.Count - 1
If .Rows(i)("name") & "" <> "" Then
temp &= .Rows(i)("name") & ", "
End If
Next
End With
temp = temp.Trim(",")
testing &= "&Name=" & temp & vbCrLf
这是在字符串的末尾得到一个逗号。但是如果我做的话
temp = temp.Trim.Trim(",")
删除所有逗号。
如何保留所有逗号并仅删除最后一个逗号?
答案 0 :(得分:14)
temp = temp.Trim().Substring(0, temp.Length - 1)
或
temp = temp.Trim().Remove(temp.Length - 1)
答案 1 :(得分:11)
temp = temp.TrimEnd(CChar(","))
那会做到这一点,我认为这是最简单的方法。
答案 2 :(得分:3)
如果在循环中设置分隔符
,则可以避免使用修剪/额外字符Dim delimiter as string = ""
For i As Integer = 0 To .Rows.Count - 1
If .Rows(i)("name") & "" <> "" Then
temp &= delimiter & .Rows(i)("name")
delimiter = ","
End If
Next
答案 3 :(得分:1)
Trim()
函数上有Char()
(静态字符数组)参数,您不需要明确传递Char
。
' VB.Net Version
", Hello ^_^ ^_^ ,,, , ,, ,, ,".Trim({" "c, ","c})
//C# version
", Hello ^_^ ^_^ ,,, , ,, ,, ,".Trim({' ', ','})
会产生输出
"Hello ^_^ ^_^"
多参数.Trim()
从字符串的开头和结尾删除指定的字符。如果您只想删除开头或结尾,请分别使用.TrimStart()
或.TrimEnd()
。
答案 4 :(得分:1)
这有效:
dim AlarmStr as string="aaa , bbb , ccc , "
AlarmStr = AlarmStr.Remove(AlarmStr.LastIndexOf(","))
答案 5 :(得分:0)
在添加最后一个逗号之前检查循环是否完成。 #cleaner
While dr.Read
For c As Integer = 0 To dr.FieldCount - 1
s.Append(dr(c).ToString.Trim)
'This line checks if the loop is ending before adding a comma
If (c < dr.FieldCount - 1) Then s.Append(",")
Next
s.Append(vbCrLf)
End While
答案 6 :(得分:0)
我想知道,基于OP的代码示例,没有人建议使用String.Join
或使用StringBuilder
构建输出
Dim names As New List(Of String)
With ad.Tables(2)
For i As Integer = 0 To .Rows.Count - 1
' DataRow("columnName").ToString() returns value or empty string if value is DbNull
If .Rows(i)("name").ToString() <> "" Then
names.Add(.Rows(i)("name"))
End If
Next
End With
Dim temp As String = String.Join(", ", names)
testing &= "&Name=" & temp & vbCrLf
使用LINQ和DataRow
扩展方法.Field(Of T)
,代码看起来更简单
Dim names = ad.Tables(2).
AsEnumerable().
Select(row => row.Field<String>("name")).
Where(name => String.IsNullOrEmpty(name) = False)
Dim temp As String = String.Join(", ", names)
testing &= "&Name=" & temp & vbCrLf
如果走得更远,您可以(应该)使用StringBuilder
构建字符串,并使用Aggregate
方法从集合中构建字符串
答案 7 :(得分:-1)
temp = temp.TrimEnd()
这会从字符串中修剪尾随空格。
答案 8 :(得分:-1)
我知道有点奇怪,但我发现这对我有用:
Visual Basic:
每次:mystring =&#34;今天,我喜欢出去,,,,&#34; (少于五个逗号和空格)
mystring.Trim.TrimEnd(",").Trim.TrimEnd(",").Trim.TrimEnd(",").Trim.TrimEnd(",").Trim.TrimEnd(",")