2012-04-05 71 views
25

您好,我正在嘗試從字符串中刪除所有特定字符。我一直在使用String.Replace,但它沒有什麼,我不知道爲什麼。這是我現在的代碼。如何從字符串中刪除特定字符的所有實例

public string color; 
    public string Gamertag2; 
    private void imcbxColor_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     uint num; 
     XboxManager manager = new XboxManagerClass(); 
     XboxConsole console = manager.OpenConsole(cbxConsole.Text); 
     byte[] Gamertag = new byte[32]; 
     console.DebugTarget.GetMemory(0x8394a25c, 32, Gamertag, out num); 
     Gamertag2 = Encoding.ASCII.GetString(Gamertag); 
     if (Gamertag2.Contains("^")) 
     { 
      Gamertag2.Replace("^" + 1, ""); 
     } 
     color = "^" + imcbxColor.SelectedIndex.ToString() + Gamertag2; 
     byte[] gtColor = Encoding.ASCII.GetBytes(color); 
     Array.Resize<byte>(ref gtColor, gtColor.Length + 1); 
     console.DebugTarget.SetMemory(0x8394a25c, (uint)gtColor.Length, gtColor, out num); 
    } 

它基本上從我的Xbox 360中檢索字符串的字節值,然後將其轉換爲字符串形式。但我希望它刪除「^」的所有實例String.Replace似乎沒有工作。它絕對沒有。它只是像以前一樣留下字符串。任何人都可以向我解釋爲什麼它會這樣嗎?

+0

你試過正則表達式嗎? – Sandeep 2012-04-05 02:16:03

+2

@Sandeep正則表達式會過度簡化一個簡單的問題。 – Amicable 2014-04-17 12:53:12

回答

51

必須的String.Replace的返回值分配到原來的字符串實例:

因此而不是(無需爲Contains check)

if (Gamertag2.Contains("^")) 
{ 
    Gamertag2.Replace("^" + 1, ""); 
} 

只是這(那是什麼神祕+1):

Gamertag2 = Gamertag2.Replace("^", ""); 
+4

@Ian - 我不相信。除非你沒有告訴我們什麼,'Gamertag2 = Gamertag2.Replace(「^」,「」);''一定會刪除任何「^」的實例。在'String.Replace'後面設置一個斷點,看它是否從'Gamertag2'中刪除了「^」。 – climbage 2012-04-05 02:37:59

+2

一個字符串是不可變的 - 這意味着你需要將它分配給某個東西。 .Replace會返回一個新的字符串。 – Shumii 2015-01-13 15:40:27

10

兩件事:

1)C#字符串是不可變的。您需要這樣做:

Gamertag2 = Gamertag2.Replace("^" + 1, ""); 

2)"^" + 1?你爲什麼做這個?你基本上是說Gamertag2.Replace("^1", "");,我敢肯定你不是你想要的。

1

喜歡爬蟲說,你的問題肯定是

Gamertag2.Replace("^"+1,""); 

該行只會從字符串中刪除「^ 1」的實例。如果你想刪除所有「^」的實例,你想要的是:

Gamertag2.Replace("^",""); 
相關問題