Non credevo a Bittercode come ha detto che LINQ avrebbe sovraperformato regex. Quindi ho fatto un piccolo test solo per essere sicuro.
tre esempi di come fare questo:
Dim _invalidChars As Char() = New Char() {"j"c, "a"c, "n"c}
Dim _textToStrip As String = "The quick brown fox jumps over the lazy dog"
Private Sub btnStripInvalidCharsLINQ_Click(sender As System.Object, e As System.EventArgs) Handles btnStripInvalidCharsLINQ.Click
Dim stripped As String = String.Empty
Dim sw As Stopwatch = Stopwatch.StartNew
For i As Integer = 0 To 10000
stripped = _textToStrip.Where(Function(c As Char) Not _invalidChars.Contains(c)).ToArray
Next
sw.Stop()
lblStripInvalidCharsLINQ.Text = _stripped & " - in " & sw.Elapsed.TotalMilliseconds & " ms"
End Sub
Private Sub btnStripInvalidCharsFOR_Click(sender As System.Object, e As System.EventArgs) Handles btnStripInvalidCharsFOR.Click
Dim stripped As String = String.Empty
Dim sw As Stopwatch = Stopwatch.StartNew
stripped = _textToStrip
For i As Integer = 0 To 10000
For Each c As Char In _invalidChars
stripped = stripped.Replace(c, "")
Next
Next
sw.Stop()
lblStipInvalidcharsFor.Text = stripped & " - in " & sw.Elapsed.TotalMilliseconds & " ms"
End Sub
Private Sub btnStripInvalidCharsREGEX_Click(sender As System.Object, e As System.EventArgs) Handles btnStripInvalidCharsREGEX.Click
Dim stripped As String = String.Empty
Dim sw As Stopwatch = Stopwatch.StartNew
For i As Integer = 0 To 10000
stripped = Regex.Replace(_textToStrip, "[" & New String(_invalidChars) & "]", String.Empty)
Next
sw.Stop()
lblStripInvalidCharsRegex.Text = stripped & " - in " & sw.Elapsed.TotalMilliseconds & " ms"
End Sub
I risultati:
Così, il ciclo for con String.Replace outperformes tutti gli altri metodi.
Per questo motivo, creerò una funzione di estensione dell'oggetto stringa.
Module StringExtensions
<Extension()> _
Public Function ReplaceAll(ByVal InputValue As String, ByVal chars As Char(), replaceWith As Char) As String
Dim ret As String = String.Empty
For Each c As Char In chars
ret.Replace(c, replaceWith)
Next
Return ret
End Function
allora si potrebbe utilizzare questa funzione piacevole e essere letti in una sola riga:
_textToStrip.ReplaceAll(_invalidChars, CChar(String.Empty))
Questo è un caso di "dovrebbe avere chiesto la domanda esatta invece di riformularlo". Per elaborare, in realtà ho una stringa che è fondamentalmente una serie di parole, separate da spazi. Ho una serie di parole che voglio eliminare dalla stringa, quindi perché ho pensato che il foreach sarebbe stato possibile/utile. Quando la (diversa) domanda viene posta in questo modo, Regex non è adatto. quindi in pratica: dim words() come stringa = ("the", "brown", "pigro") dim frase come stringa = "il rapido brown fox jump" results = "quick fox jumps" la mia speranza era per words.ForEach (Function (w) sentence.Replace (w, "") – hitch