Replacing bad characters of a String with bad characters

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

提交回复
热议问题