views:

4865

answers:

6

In C#, can I convert a string value to a string literal, the way I would see it in code? I would like to replace tabs, newlines, etc. with their escape sequences.

If this code:

Console.WriteLine(someString);

produces:

Hello
World!

I want this code:

Console.WriteLine(ToLiteral(someString));

to produce:

\tHello\r\n\tWorld!\r\n
A: 

I don't know any built-in function for this. And it does sense, because the escape sequences are diferent in diferent languages ( c#, vb.net, etc ... ). You must search for it in internet or write your own. It's not dificult :).

TcKs
Good point that the escape sequences are different for different languages.
Hallgrim
+8  A: 

Interesting question. Would deserve an up vote, if I could give it.

If you can't find a better method, you can always replace. If you go that way, you could use this:

Listing of the C# Escape sequences

Nelson Reis
+11  A: 

EDIT: A more structured approach, including all escape sequences for strings and chars.
Doesn't replace unicode characters with their literal equivalent. Doesn't cook eggs, either.

public class ReplaceString
{
    static readonly IDictionary<string, string> m_replaceDict 
        = new Dictionary<string, string>();

    const string ms_regexEscapes = @"[\a\b\f\n\r\t\v\\""]";

    public static string StringLiteral(string i_string)
    {
        return Regex.Replace(i_string, ms_regexEscapes, match);
    }

    public static string CharLiteral(char c)
    {
        return c == '\'' ? @"'\''" : string.Format("'{0}'", c);
    }

    private static string match(Match m)
    {
        string match = m.ToString();
        if (m_replaceDict.ContainsKey(match))
        {
            return m_replaceDict[match];
        }

        throw new NotSupportedException();
    }

    static ReplaceString()
    {
        m_replaceDict.Add("\a", @"\a");
        m_replaceDict.Add("\b", @"\b");
        m_replaceDict.Add("\f", @"\f");
        m_replaceDict.Add("\n", @"\n");
        m_replaceDict.Add("\r", @"\r");
        m_replaceDict.Add("\t", @"\t");
        m_replaceDict.Add("\v", @"\v");

        m_replaceDict.Add("\\", @"\\");
        m_replaceDict.Add("\0", @"\0");

        //The SO parser gets fooled by the verbatim version 
        //of the string to replace - @"\"""
        //so use the 'regular' version
        m_replaceDict.Add("\"", "\\\""); 
    }

    static void Main(string[] args){

        string s = "here's a \"\n\tstring\" to test";
        Console.WriteLine(ReplaceString.StringLiteral(s));
        Console.WriteLine(ReplaceString.CharLiteral('c'));
        Console.WriteLine(ReplaceString.CharLiteral('\''));

    }
}
Cristi Diaconescu
This is not all escape sequences ;)
TcKs
It's a good starting point, though.
Dave Van den Eynde
A: 

Code:

string someString1 = "\tHello\r\n\tWorld!\r\n";
string someString2 = @"\tHello\r\n\tWorld!\r\n";

Console.WriteLine(someString1);
Console.WriteLine(someString2);

Output:

    Hello
    World!

\tHello\r\n\tWorld!\r\n

Is this what you want?

Nazgulled
I have someString1, but it is read from a file. I want it to appear as someString2 after calling some method.
Hallgrim
+8  A: 
public static class StringHelpers
{
    private static Dictionary<string, string> escapeMapping = new Dictionary<string, string>()
    {
        {"\"", @"\\\""},
        {"\\\\", @"\\"},
        {"\a", @"\a"},
        {"\b", @"\b"},
        {"\f", @"\f"},
        {"\n", @"\n"},
        {"\r", @"\r"},
        {"\t", @"\t"},
        {"\v", @"\v"},
        {"\0", @"\0"},
    };

    private static Regex escapeRegex = new Regex(string.Join("|", escapeMapping.Keys.ToArray()));

    public static string Escape(this string s)
    {
        return escapeRegex.Replace(s, EscapeMatchEval);
    }

    private static string EscapeMatchEval(Match m)
    {
        if (escapeMapping.ContainsKey(m.Value))
        {
            return escapeMapping[m.Value];
        }
        return escapeMapping[Regex.Escape(m.Value)];
    }
}
ICR
One of your strings is not properly closed.Try{"\"", "\\\""},as the first line of your dictionary instead.
luiscubal
+15  A: 

I found this:

static string ToLiteral(string input)
    {
        var writer = new StringWriter();
        CSharpCodeProvider provider = new CSharpCodeProvider();
        provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
        return writer.GetStringBuilder().ToString();
    }

This code:

var input = "\tHello\r\n\tWorld!";
Console.WriteLine(input);
Console.WriteLine(ToLiteral(input));

Produces:

    Hello
    World!
"\tHello\r\n\tWorld!"
Hallgrim
Just found this from google the subject. This has to be best, no point in reinventing stuff that .net can do for us
Andy Morris
Nice one, but be aware that for longer strings, this will insert "+" operators, newlines and indentation. I couldn't find a way to turn that off.
Timwi
Oh, also — the ".GetStringBuilder()" is redundant. You can just use .ToString() directly on a StringWriter.
Timwi