Escape Characters
In this chapter you will learn:
- How to escape characters in String
- Character escape sequence: \0
- Escape sequences in strings: embed quotes
- Escape sequences in strings: \t (tab)
- Escape sequences in strings: \n (new line)
Escape strings
Escape Sequence | Character Name | Unicode Encoding |
---|---|---|
\' | Single quote | 0x0027 |
\" | Double quote | 0x0022 |
\\ | Backslash | 0x005C |
\0 | Null | 0x0000 |
\a | Alert | 0x0007 |
\b | Backspace | 0x0008 |
\f | Form feed | 0x000C |
\n | newline | 0x000A |
\r | Carriage return | 0x000D |
\t | Horizontal tab | 0x0009 |
\v | Vertical tab | 0x000B |
\uxxxx | Unicode character in hex | \u0029 |
using System;//from j a v a 2 s. c om
public class MainClass
{
public static void Main()
{
Console.WriteLine("Single quote \\': {0} ({1})", '\'', (int)'\'');
Console.WriteLine("Double quote \\\": {0} ({1})", '\"', (int)'\"');
Console.WriteLine("Backslash \\\\: {0} ({1})", '\\', (int)'\\');
Console.WriteLine("Unicode null \\0: {0} ({1})", '\0', (int)'\0');
Console.WriteLine("Alert \\a: {0} ({1})", '\a', (int)'\a');
Console.WriteLine("Backspace \\b: {0} ({1})", '\b', (int)'\b');
Console.WriteLine("Horizontal tab \\t: {0} ({1})", '\t', (int)'\t');
Console.WriteLine("Newline \\r: {0} ({1})", '\r', (int)'\r');
Console.WriteLine("Vertical quote \\v: {0} ({1})", '\v', (int)'\v');
Console.WriteLine("Form feed \\f: {0} ({1})", '\f', (int)'\f');
Console.WriteLine("Carriage return \\r: {0} ({1})", '\r', (int)'\r');
}
}
The code above generates the following result.
Character escape sequence: \0
using System;//j ava 2 s . co m
class MainClass
{
static void Main(string[] args)
{
char MyChar = '\0';
Console.WriteLine(MyChar);
}
}
Escape sequences in strings: embed quotes
using System; //from j ava 2s . c o m
class Example {
public static void Main() {
Console.WriteLine("\"Why?\", he asked.");
}
}
The code above generates the following result.
Escape sequences in strings: \t (tab)
using System; //j a v a2s. co m
class Example {
public static void Main() {
Console.WriteLine("One\tTwo\tThree");
Console.WriteLine("Four\tFive\tSix");
}
}
The code above generates the following result.
Escape sequences in strings: \n (new line)
using System; /* j av a 2 s .c o m*/
class Example {
public static void Main() {
Console.WriteLine("Line One\nLine Two\nLine Three");
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » String