Converts a string into C# string-literal format (ready to be pasted into a program), including the double quotes. - CSharp System

CSharp examples for System:String Parse

Description

Converts a string into C# string-literal format (ready to be pasted into a program), including the double quotes.

Demo Code


using System.Linq;
using System.Collections.Generic;

public class Main{
        /// <summary>
        /// Converts a string into C# string-literal format (ready to be pasted into a program), including the double quotes.
        /// </summary>
        public static string Show(this string s)
        {//from   w w  w  .ja  v  a  2  s .  c  om
            return string.Format("\"{0}\"", s.SelectMany(c => c.ShowLitChar())
                                             .AsString()
                                             .Replace("\"", "\\\""));
        }
        /// <summary>
        /// Converts a character into C# character-literal format (ready to be pasted into a program), including the single quotes.
        /// </summary>
        public static string Show(this char c)
        {
            if (c == '\'')
                return @"'\''";
            else
                return string.Format("'{0}'", c.ShowLitChar());
        }
        public static string AsString(this IEnumerable<char> chars)
        {
            return new string(chars.ToArray());
        }
        public static string ShowLitChar(this char c)
        {
            if (c == '\\')
                return @"\\";
            else if (c >= ' ')
                return c.ToString();

            switch (c)
            {
                case '\a':
                    return @"\a";
                case '\b':
                    return @"\b";
                case '\f':
                    return @"\f";
                case '\n':
                    return @"\n";
                case '\r':
                    return @"\r";
                case '\t':
                    return @"\t";
                case '\v':
                    return @"\v";
                default:
                    return string.Format(@"\x{0:X2}", (int)c);
            }
        }
}

Related Tutorials