mattg
mattg

Reputation: 51

How do you get StringBuilder's ToString method to not escape the escape characters in a string?

Thanks to NgM I am using StringBuilder in .NET 3.5 to find and escape special chars. However, when I use the ToString method, it escapes the escape chars which then makes the previous exercise useless. Anyone know how to get around that?

Here is the code:

    private String ParseAndEscapeSpecialChars(String input)
    {
        StringBuilder sBuilder = new StringBuilder(input);
        String output;
        String specialChars = @"([-\]\[<>\?\*\\\""/\|\~\(\)\#/=><+\%&\^\'])";
        Regex expression = new Regex(specialChars);

        if (expression.IsMatch(input))
        {
            sBuilder.Replace(@"\", @"\\");
            sBuilder.Replace(@"'", @"\'");                
        }

        output = sBuilder.ToString();
        return output;
    }

Here are the results from debug:

input       "005 - SomeCompany's/OtherCompany's Support Center"
sBuilder    {005 - SomeCompany\'s/OtherCompany\'s Support Center}
output      "005 - SomeCompany\\'s/OtherCompany\\'s Support Center"

Upvotes: 5

Views: 6718

Answers (2)

blowdart
blowdart

Reputation: 56550

You say your results are from debug. If by that you mean the debugger itself, by examining the string contents by hovering over the variable or putting it on a watch list in VS then the debugger display will escape the slashes in its windows/tooltips. However if you actually output the string in your code you will see the escaping is not there - it's just a debugger "feature".

Try

System.Diagnostics.Debug.Writeline(myOutputVariable);

and look in the output window to see the "real" contents.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1503649

StringBuilder doesn't escape characters. It does nothing special or clever. Dollars to doughnuts you're just seeing this in the debugger, which does show you an escaped version.

Upvotes: 7

Related Questions