我有一個字串變數,它應該包含如下例所示的值:
Dim xStr as string = "13,14,133,15,2500,25"
我需要從中洗掉一個非常具體的值,比如“13”,但是當我使用替換函式時,我有很多限制,因為如果我用空替換“13”,結果將是“,14,3,15,2500 ,25"。這是錯誤的,因為我只需要洗掉 13 和它后面的逗號(如果它在那里)。
我該如何申請?
uj5u.com熱心網友回復:
我會將字串拆分為單獨的數字(仍然是字串),然后使用 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
uj5u.com熱心網友回復:
好吧,我們必須在這里做一些假設。
但是,一個額外的(雜散)空間 - 是的,我們應該處理這個問題。
如果只有一個沒有逗號的條目是洗掉號,我們也支持。
所以,這很有效:
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,>
因此,上述內容也適用于分隔符的“空”值。
如果我們要受到懲罰,我們可能可以用一行來寫整個交易,但我建議如果你經常使用這段代碼,那么我們就用這個
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
uj5u.com熱心網友回復:
試試這個,
完成: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"
uj5u.com熱心網友回復:
嘗試這個:
Dim xStr as string = "13,14,133,15,2500,25"
xStr = xStr.Remove(0, xStr.IndexOf(",") 1).Trim()
如果這回答了您的問題,請接受答案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/335589.html
上一篇:修改字串中兩個符號之間的字符
下一篇:如何識別字串中的特殊字符?C#
