[英]Not removing a substring from a string
我试图在此简单代码中从字符串中删除子字符串。 但是c#并没有将其删除:
stringCmd = "Haha WoWI am in love!"
stringCmd.Remove(stringCmd.IndexOf("WoW"), 5);
删除后应该是“哈哈恋爱了!”
字符串在.NET中是不可变的
stringCmd = "Haha WoWI am in love!"
stringCmd = stringCmd.Remove(stringCmd.IndexOf("WoW"), 5);
string.Remove
方法返回新字符串,而不修改作为参数传递的字符串,因此您必须将其分配回变量:
stringCmd = stringCmd.Remove(stringCmd.IndexOf("WoW"), 5);
您还应该注意,.NET中的string
s是不可变的。 您可以在MSDN上阅读有关此内容的更多信息: string
(C#参考) 。
字符串是不可变的,因此它不会影响字符串,而是返回一个新字符串:
string stringCmd = "Haha WoWI am in love!"
string modified = stringCmd.Remove(stringCmd.IndexOf("WoW"), 5);
Console.WriteLine(modified);
此方法返回除去指定子字符串的字符串。 因此,您需要将其应用于另一个字符串:
string myString = stringCmd.Remove(stringCmd.IndexOf("WoW"), 5);
或者您可以将其应用回自身:
stringCmd = stringCmd.Remove(stringCmd.IndexOf("WoW"), 5);
我会尝试做stringCmd = stringCmd.Remove(stringCmd.IndexOf(“ WoW”),5);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.