c# - 为什么 String.Replace 不替换任何东西?

标签 c#

<分区>

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

Write a method that removes all occurrences of a string from another string:

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

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

    }

我在这里所做的显然没有用,但我不知道在哪里搜索如何执行此操作。

最佳答案

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

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

Assert.AreEqual( "abc", foo         );
Assert.AreEqual( "ac" , fooWithoutB );

一些其他注意事项:

  • 避免使用“匈牙利表示法”(例如变量名的 str 前缀)。不鼓励这样做。
  • 使用有意义的名称。 str 没有告诉我它的用途。考虑像 RemoveAllOcurrences(String needle, String haystack)(String ofThis, String fromThis) 这样的签名。
  • 您的原始方法返回原始第二个参数不变。如果您使用 IDE 的逐步调试器,您可能已经发现了这个错误。

关于c# - 为什么 String.Replace 不替换任何东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40771942/

相关文章:

c# - ElasticSearch 按具有默认值的子字段对父文档进行评分

C# 如何判断 IEnumerable 是否可变?

c# - 如何使用 Mock.Of<T>() 模拟没有默认构造函数的类?

c# - 卡在 while 循环中

c# - .net 中的 [] 括号是什么?

c# - 使用 HTMLAgilityPack 登录网站

c# - 存储/设置 C# 应用程序配置设置的最佳方式是什么?

c# - 隐式委托(delegate)转换

c# - 带日期的 Subsonic 3.0 ActiveRecord

c# - 在固定位置显示 WPF 验证错误消息