为什么不是String.Replace替换任何东西?

Del*_*ell 2 c#

这是其中一个问题.基本上我卡住了.

编写一个方法,从另一个字符串中删除所有出现的字符串:

    [Test]
    public void TestExercise12()
    {
        Programmeren2Tests.Chapter12Test.TestExercise12(Exercise12);
    }

    public static string Exercise12(string strToRemove, string str)
    {
        strToRemove.Replace("str", "x");
        return str;

    }
Run Code Online (Sandbox Code Playgroud)

我在这里做了什么显然没有用,但我不知道在哪里搜索如何做到这一点.

Dai*_*Dai 5

字符串在C#/ .NET中是不可变的,因此foo.Replace不会更新值foo,而是返回一个新值:

String foo         = "abc";
String fooWithoutB = foo.Replace( "b", "" );

Assert.AreEqual( "abc", foo         );
Assert.AreEqual( "ac" , fooWithoutB );
Run Code Online (Sandbox Code Playgroud)

其他几点说明:

  • 避免使用"匈牙利表示法"(例如str变量名称的前缀).这是不鼓励的.
  • 用有意义的名字.str并没有告诉我它的用途.考虑签名RemoveAllOcurrences(String needle, String haystack)(String ofThis, String fromThis)代替.
  • 原始方法返回原始第二个参数不变.如果您使用IDE的逐步调试器,则可能已经识别出此错误.