【发布时间】:2010-11-22 21:05:23
【问题描述】:
使用 VB.NET,我希望能够在一行代码中替换字符串中的一系列字符。
例如,类似:
Dim charsToReplace as string = "acegi"
Dim stringToBeReplaced as string = "abcdefghijklmnop"
charsToReplace.ToArray().ForEach(Function (c) stringTobeReplaced = stringTobeReplaced.Replace(c, ""))
但是,这不起作用。
以下确实有效,但我不希望字符串成为类级别变量:
Sub Main()
Dim toReplace As String = "acegikmoq"
Console.WriteLine(mainString)
Dim chars As List(Of Char) = toReplace.ToList()
chars.ForEach(AddressOf replaceVal)
Console.WriteLine(mainString)
Console.ReadLine()
End Sub
Dim mainString As String = "this is my string that has values in it that I am going to quickly replace all of..."
Sub replaceVal(ByVal c As Char)
mainString = mainString.Replace(c, "")
End Sub
这个可以吗?
【问题讨论】:
-
这是一个“应该问确切的问题而不是改写它”的案例。详细地说,我实际上有一个字符串,它基本上是一系列单词,用空格分隔。我有一组单词要从字符串中删除,因此我认为 foreach 可能/有用。当以这种方式提出(不同的)问题时,Regex 不适合。所以基本上:dim words() as string = ("the", "brown", "lazy") dim sentence as string = "the quick brown fox jumps" results="quick fox jumps" 我希望是 words.ForEach(函数(w)句.Replace(w, "")