如何从字符串中删除特定字符的所有实例
您好我正在尝试从字符串中删除所有特定字符。 我一直在使用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(ref gtColor, gtColor.Length + 1); console.DebugTarget.SetMemory(0x8394a25c, (uint)gtColor.Length, gtColor, out num); }
它基本上从我的Xbox 360中检索字符串的字节值,然后将其转换为字符串forms。 但我希望它删除所有“^” String.Replace
实例似乎不起作用。 它什么都没做。 它只是留下以前的字符串。 任何人都可以向我解释它为什么这样做?
您必须将String.Replace
的返回值分配给原始字符串实例:
因此而不是(不需要Contains check)
if (Gamertag2.Contains("^")) { Gamertag2.Replace("^" + 1, ""); }
就是这个(什么是神秘的+1
?):
Gamertag2 = Gamertag2.Replace("^", "");
两件事情:
1)C#字符串是不可变的。 你需要这样做:
Gamertag2 = Gamertag2.Replace("^" + 1, "");
2) "^" + 1
? 你为什么做这个? 你基本上是在说Gamertag2.Replace("^1", "");
我肯定不是你想要的。
就像攀岩说的那样,你的问题肯定是
Gamertag2.Replace("^"+1,"");
该行只会从字符串中删除“^ 1”的实例。 如果要删除“^”的所有实例,您需要的是:
Gamertag2.Replace("^","");