我有一个字符串变量,它应该包含如下示例中的值:
Dim xStr as string = "13,14,133,15,2500,25"
我需要删除一个非常特定的值,比如"13",但是当我使用替换函数时,我有很多限制,因为如果我替换"13"如果为空,结果将是", 14,3,15,255,25 "。这是错误的,因为我只需要删除13和它后面的逗号,如果它在那里。
我如何应用它?
我会将字符串分成单独的数字(仍然是字符串),然后使用Step -1进行反向For循环,这样我们就不会得到超出范围的索引。
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim xStr As String = "13,14,133,15,2500,25"
Dim numToRemove As String = "13"
Dim nums = xStr.Split(","c).ToList
For index = nums.Count - 1 To 0 Step -1
If nums(index) = numToRemove Then
nums.RemoveAt(index)
End If
Next
Dim NewString = String.Join(",", nums)
MessageBox.Show(NewString)
End Sub
嗯,我们必须在这里做一些假设。
但是,一个额外的(偏离的)空格-是的,我们应该处理它。
我们也支持,如果只有一个条目没有逗号是删除号。
所以,这个工作得很好:
Dim strToRemove As String = "14"
Dim str = "13,14 ,133,15,2500,25,"
str = str.Replace(" ", "")
Dim strL As List(Of String) = str.Split(",").ToList
strL.RemoveAll(Function(xRow) xRow = strToRemove)
str = Join(strL.ToArray(), ",")
Debug.Print("<" & str & ">")
输出:
<13,133,15,2500,25,>
以上也适用于"empty"分隔符的值。
如果我们受到惩罚,我们可能会用一行写完整个交易,但我建议如果你经常使用这段代码,那么我们就用这个
Public Function RemoveToken(str as string, sRemove as string) as string
str = str.Replace(" ", "")
Dim strL As List(Of String) = str.Split(",").ToList
strL.RemoveAll(Function(xRow) xRow = sRemove)
return Join(strL.ToArray(), ",")
End Function
试试这个
使用:Replace
,TrimStart
和TrimEnd
方法完成。
'A string sample
Dim xStr as string = "33, 13, , 14 ,133 ,15, 2500 ,25"
'Put a number to remove here
Dim number_to_remove=13
xStr = xStr.Replace(" ","") ' Removing any unnecessary whitespace
xStr=","+xStr+"," ' Adding a padding comma
Console.WriteLine(xStr)
' Removing wanted number
xStr = xStr.Replace("," + Cstr(number_to_remove) + "," ,",")
' Removing any unnecessary comma
if xStr.StartsWith(",") then ' Remove coma At the beginning
xStr = xStr.trimstart(",")
end if
if xStr.EndsWith(",") then ' Remove coma At the end
xStr = xStr.trimend(",")
end if
xStr = xStr.Replace(",,",",") ' Remove coma in the middle
Console.WriteLine(xStr)
输入()
注意,输入被处理为容忍spaces
和empty
元素。
"33, 13, , 14 ,133 ,15, 2500 ,25"
在本例中,要删除的号码是13
。
输出()
"33,14,133,15,2500,25"
试试这个:
Dim xStr as string = "13,14,133,15,2500,25"
xStr = xStr.Remove(0, xStr.IndexOf(",") + 1).Trim()