Escape Sequences in C#
Escape sequences are special characters that allow you to include non-printable characters within strings. They come in handy when you need to represent characters that cannot be typed directly into a string, such as tabs (insert one-character blank space), newline, or quotes(“ “). In C#, escape sequences are denoted by a backslash (\) followed by a specific character that holds special meaning for the compiler.
Escape Sequence | Description | Example | Output |
\” | Output a double quote | “\”Hello\”” | “Hello” |
\\ | Output a backslash. Usually used for defining a path on the server e.g., C:\Windows | “C:\\Windows” | C:\Windows |
\n | Insert a new line | “Line1\nLine2” | Line1 Line2 |
\r | Insert a carriage-return, delete previous word | “Hello\rWorld” | World |
\t | Insert a tab | “Hello\tWorld” | Hello World |
\0 | Add null character between hello and world | “Hello\0World” | Hello World |
\b | Insert a backspace i.e. delete 1 character before \b | “Hello\bWorld” | HellWorld |
Verbatim strings are used to avoid using escape sequences. i.e. in case you want to write a character that is an escape sequence then we use verbatim strings to let the program know to avoid the escape sequence command created by prefixing a string literal with the @ symbol.
Verbatim String | Description | Example | Output |
@”…” | Verbatim string with newline | @”Hello\nWorld” | Hello\nWorld |
Course Video
Task
1. Write a C# program that prints the following text using escape sequences
Hello, it’s a beautiful day!
“Programming is fun,” she said.
2. Write a C# program that prints the file path C:\Program Files\MyApp using escape sequences.
3. Write a C# program that prints the following table using escape sequences the existing format is like this – NameAgeAlice30Bob25
Expected Output :
Name Age
Alice 30
Bob 25
4. Write a C# program that demonstrates the use of the carriage return \r to replace part of a string. The initial string should be Goodbye and after applying \r, it should be Hello.
5. Write a C# program that uses the backspace \b escape sequence to correct the following string from Helllo World to Hello World.
6. Write a C# program that inserts a null character \0 between two words and prints the string. The output should demonstrate that the null character does not affect the visible output. For example, the string should be Hello\0World.
7. Write a C# program that prints the string Hello\nWorld exactly as it is, without interpreting the \n as a newline character.