2009-08-26 83 views
11

使用VB.NET我希望能夠用一行代碼替換字符串中的一系列字符。用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 

可以這樣做?

+0

這是一個「應該問精確問題而不是改寫它」的情況。詳細說來,我實際上有一個字符串,它基本上是一系列由空格分隔的單詞。我有一串我想從字符串中刪除的單詞,因此我認爲爲什麼我認爲每個foreach都可能/有用。當以這種方式詢問(不同的)問題時,正則表達式不適用。所以基本上: dim words()as string =(「the」,「brown」,「lazy」) dim sentence as string =「快速棕色狐狸跳躍」 results =「快速狐狸跳躍」 我的希望是words.ForEach(Function(w)sentence.Replace(w,「」) – hitch 2009-08-26 06:45:41

回答

1

String類有一個替換方法來做到這一點。你可以這樣使用它:

YourString = YourString.Replace("OldValue", "NewValue") 
+0

我可能還沒有完全清楚,但我想替換字符串中每個字符的每個實例,即 chars =「ace」 longString = 「abcdeabcdeabcde」 結果=「bdbdbd」 取而代之的是不是能夠做到這一點 – hitch 2009-08-26 06:42:03

+0

您實際上可以使用替換不止一次在相同的語句:。 myDate2 = Date.Now.ToString(「S」)更換(「:」,「 - 」)。替換(「T」,「」 ) – 2015-12-24 16:24:40

24

如果我正確讀了這個,你試圖從字符串中去掉一個字符列表。這非常適合RegEx。

Console.WriteLine(Regex.Replace("abcdefghijklmnop", "[acegi]", string.Empty)) 

(你需要導入System.Text.RegularExpressions)

+0

如果經常使用該方法的性能如何? – serhio 2013-05-06 10:31:31

+0

@serhio:正則表達式其實是用於字符串操作的。無論你用什麼來處理字符串,正則表達式的速度更快,並且使用更少的資源。 – 2013-08-14 13:10:56

+0

@SimonDugré如我的回答(這是比你的評論早)所示,這是相反的。正則表達式要慢得多。 – JDC 2017-10-17 11:54:42

1

我建議喬恩·加洛韋的做法,正則表達式是適當的方法,以及未來開發商將感謝你的:) - 儘管Linq也不是一個難以解決的問題。下面是一些(未經測試)C#代碼來做到這一點:

string stringToBeReplaced = "abcdefghijklmnop"; 
string charsToReplace = "acegi"; 
stringToBeReplaced = new String(stringToBeReplaced.Where(c => !charsToReplace.Any(rc => c == rc)).ToArray()); 

我懷疑這可能是代碼執行會稍微好一點,然後正則表達式等價的,如果性能是一個問題。

6

正則表達式的方法是最適合的,但我真的需要說的是:

請,爲維護開發商的愛,不要掛斷上得到這個下降到1行代碼。一個方法調用是你的真正目標,如果你最終只是將一堆調用堆成一行來表示它是單行的,那麼你就是在自己的腳下開槍。

+0

這不是我的主要目標,因爲它的發展目的只有一條路線,更多的是因爲「我的帽子裏有一隻蜜蜂,因爲它不適合我的想法,並且想知道如何去做」的目的。 .. :) – hitch 2009-08-26 06:40:32

+3

+1爲維護開發商 - 在那裏,做到這一點,有這樣的頭痛! =) – Rob 2009-08-26 06:42:32

5

我不相信Bittercode,因爲他說LINQ將超越正則表達式。 所以我做了一個小測試只是爲了確定。如何做到這一點

三個例子:

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 

結果:

Performance results

所以,for循環與outperformes與string.replace所有其他方法。

因此,我會對字符串對象做一個擴展函數。

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 

然後,你可以使用這個功能不錯,可讀取一行:

_textToStrip.ReplaceAll(_invalidChars, CChar(String.Empty)) 
0

什麼是重複行語句,如果你真的想使用該代碼的最佳方式:

Sub Main() 

    Dim myString As String = Nothing 
    Dim finalString As String = Nothing 
    Console.Write("Please enter a string: ") 'your free to put anything 
    myString = Console.ReadLine() 
    finalString = myString.Replace("0", "") 
    myString = finalString 
    finalString = myString.Replace("1", "") 
    myString = finalString 
    finalString = myString.Replace("2", "") 
    myString = finalString 
    finalString = myString.Replace("3", "") 
    myString = finalString 
    finalString = myString.Replace("4", "") 
    myString = finalString 
    finalString = myString.Replace("5", "") 
    myString = finalString 
    finalString = myString.Replace("6", "") 
    myString = finalString 
    finalString = myString.Replace("7", "") 
    myString = finalString 
    finalString = myString.Replace("8", "") 
    myString = finalString 
    finalString = myString.Replace("9", "") 
    Console.WriteLine(finalString) 
    Console.ReadLine() 
End Sub 

例如:如果鍵入:012ALP456HA90BET678輸出將是:ALPHABET

+0

歡迎使用stackoverflow。請看看我對你的問題所作的編輯,以便你知道如何在將來更好地提出問題。 – Brett 2013-01-16 06:10:46

+0

遠遠不是最高效,最優雅的方法 – serhio 2013-05-06 10:29:06

0
Public Function SuperReplace(ByRef field As String, ByVal ReplaceString As String) As String 
    ' Size this as big as you need... it is zero-based by default' 
    Dim ReplaceArray(4) As String 

    'Fill each element with the character you need to replace' 

    ReplaceArray(0) = "WARD NUMBER " 
    ReplaceArray(1) = "WN " 
    ReplaceArray(2) = "WARD NO " 
    ReplaceArray(3) = "WARD-" 
    ReplaceArray(4) = "WARD " 

    Dim i As Integer 
    For i = LBound(ReplaceArray) To UBound(ReplaceArray) 
    field = Replace(field, ReplaceArray(i), ReplaceString) 
    Next i 
    SuperReplace = field 
End Function 
相關問題