I just wondered what\'s the easiest way to replace a string characters that must be replaced subsequently.
For example:
var str = \"[Hello World]\";
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();