Replacing bad characters of a String with bad characters

前端 未结 6 1391
走了就别回头了
走了就别回头了 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:21

    Here's a very uncool way to do it. But it has the advantage of being pretty close to foolproof, I think, and not using regex (in case you'd rather not use regex).

    StringBuilder sb = new StringBuilder();
    foreach (char c in str.ToCharArray()) {
        if (c == '[' || c == ']') {
            sb.Append('[' + c + ']');
        }
        else {
            sb.Append(c);
        }
    }
    string result = sb.ToString();
    
    0 讨论(0)
  • 2020-12-11 17:26
        StringBuilder result = new StringBuilder();
    
        foreach (Char singleCharacter in str)
        {
            result.Append(singleCharacter.Equals('[') ? "[[]" : singleCharacter.Equals(']') ? "[]]" : singleCharacter.ToString());
        }
    
        str = result.ToString();
    
    0 讨论(0)
  • 2020-12-11 17:29

    What about:

    str = str.Replace("[", "$1[$2")
             .Replace("]", "$1]$2")
             .Replace("$1", "[")
             .Replace("$2", "]");
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2020-12-11 17:39

    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.

    0 讨论(0)
  • 2020-12-11 17:42

    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[]]
    
    0 讨论(0)
提交回复
热议问题