Replacing bad characters of a String with bad characters

前端 未结 6 1401
走了就别回头了
走了就别回头了 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();
    

提交回复
热议问题