Replacing bad characters of a String with bad characters

前端 未结 6 1404
走了就别回头了
走了就别回头了 2020-12-11 17:12

I just wondered what\'s the easiest way to replace a string characters that must be replaced subsequently.

For example:

var str = \"[Hello World]\";         


        
6条回答
  •  一个人的身影
    2020-12-11 17:32

    What about this elegant regular expression approach:

    Regex.Replace("[Hello World]", @"[\[\]]", "[$0]");
    

    Unit test it?

    [TestMethod]
    public void UnitTestThat()
    {
        Assert.AreEqual(@"[[]Hello World[]]", Regex.Replace("[Hello World]", @"[\[\]]", "[$0]"));
    }
    

    Test passed


    Edit @JohnMcGrant

    Here is a slightly less inefficient version of your code, which has, by the way, exactly the same behaviour as the above regex:

    string result = input.Aggregate(new StringBuilder(), (a, c) =>
        -1 != "[]".IndexOf(c) ? a.AppendFormat("[{0}]", c) : a.Append(c)).ToString();
    

提交回复
热议问题