Escapes specified string against characters treated specially in string literals. E.g. '"' (quotes) and '\' (backslash). - CSharp System

CSharp examples for System:Char

Description

Escapes specified string against characters treated specially in string literals. E.g. '"' (quotes) and '\' (backslash).

Demo Code


using System.Xml.Serialization;
using System.Collections;
using System.Globalization;
using System.Collections.Specialized;
using System.Text;
using System.Collections.Generic;
using System;//from w  w  w  .j  a  v  a2  s .  c  o  m

public class Main{
        /// <summary>
		/// Escapes specified string against characters treated specially in string literals.
		/// E.g. '"' (quotes) and '\' (backslash).
		/// </summary>
		/// <param name="txt">Non-escaped string</param>
		/// <returns>Escaped string</returns>
		public static string EscapeStringForLiteral(string txt)
		{
			string res = txt;
			string[] escapeFrom = new string[] { "\\", "\"", "\t", "\r", "\n" };
			string[] escapeTo = new string[] { "\\", "\"", "t", "r", "n" }; // preceded by '\\'
			for (int i = 0; i < escapeFrom.Length; ++i)
				res = res.Replace(escapeFrom[i], "\\" + escapeTo[i]);
			return res;
		}
}

Related Tutorials