Alex Rivera | Logout

Replacing bad characters of a String with bad characters

Asked 2012-02-13T16:38:11.820
8

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

For example:

var str = "[Hello World]";
//enclose all occurences of [ and ] with brackets[] 
str = str.Replace("[","[[]").Replace("]","[]]");
  • The desired result: [[]Hello World[]]
  • The actual result: [[[]]Hello World[]]

The reason is obviously the second replace on the already modified string.

So how to replace all occurences of "bad" characters with characters that contain "bad" characters?


A quick measurement of all approaches revealed that the StringBuilder is the most efficient way.

190kb file (all in milliseconds)

  regexTime           40.5065  
  replaceTime         20.8891  
  stringBuilderTime    6.9776

7MB file

  regexTime           1209.3529           
  replaceTime          403.3985   
  stringBuilderTime    175.2583

By the way, the direct StringBuilder approach from John was twice as fast as the Aggregate approach from Sehe.

I've made an extension out of it:

public static String EncloseChars(this string input, char[] charsToEnclose, String leftSide, String rightSide) {
    if (charsToEnclose == null || leftSide == null || rightSide == null)
        throw new ArgumentException("Invalid arguments for EncloseChars", charsToEnclose == null ? "charsToEnclose" : leftSide == null ? "leftSide" : "rightSide");
    Array.Sort(charsToEnclose);
    StringBuilder sb = new StringBuilder();
    foreach (char c in input) {
        if (Array.BinarySearch(charsToEnclose, c) > -1)
            sb.Append(leftSide).A
Edit
Report

2 Answers

1

How about:

char[] replacedChars = str.SelectMany(ch => 
                                     (ch == '[' ? new char[] {'[', '[', ']'} :
                                     (ch == ']' ? new char[] {'[', ']', ']'} : 
                                     new char[] {ch}))).ToArray();
string replaced = new string(replacedChars);

Note that this avoids the multiple loops issue but creates at least as many arrays as there are characters in the input string so it might not be optimal in terms of performance.

answered 2012-02-13T16:45:05.903
0

I had the exact same problem, so I made a helper function to do just that

    protected string ReplaceUsingDictionary(string subject, Dictionary<string,string> pairs)
    {
        StringBuilder sb = new StringBuilder(subject);

        sb.Replace("{", "{{").Replace("}", "}}");

        int i=0;
        foreach (string key in pairs.Keys.ToArray())
        {
            sb.Replace(
                key.Replace("{", "{{").Replace("}", "}}"), 
                "{" + i + "}"
            );

            i++;
        }

        return string.Format(sb.ToString(), pairs.Values.ToArray());
    }

// usage
Dictionary<string, string> replacements = new Dictionary<string, string>();
replacements["["] = "[[]";
replacements["]"] = "[]]";

string mystr = ReplaceWithDictionary("[HelloWorld]", replacements); // returns [[]HelloWorld[]]
answered 2012-02-13T17:00:59.433

Your Answer