7.7. Special Characters

Aside from letters, numbers, and symbols, there is another class of characters that we will occasionally use in strings, known as special characters. These characters consist of special character combinations that all begin with a \ (backslash). They allow us to include characters in strings that would be difficult or impossible to include otherwise, such as Unicode characters that are not on our keyboards, control characters, and whitespace characters.

The most commonly-used special characters are \n and \t, which are the newline and tab characters, respectively. They work as you would expect.

Example

Console.WriteLine("A message\nbroken across lines,\n\tand indented");

Console Output

A message
broken across lines,
   and indented

We can also represent Unicode characters (most of which aren’t on a normal keyboard) using special character combinations of the form \uXXXX, where the Xs are combinations referenced by the Unicode table. This allows us to use character sets other than the basic Latin characters that English is based on, such as Greek, Cyrillic, and Arabic, as well as a wider array of symbols.

Example

Console.WriteLine("The interrobang character, \u203d, combines ? and !");
Console.WriteLine("The area of a circle is \u03C0r\u00B2");

Console Output

The interrobang character, ‽, combines ? and !
The area of a circle is πr²

We can also use the backslash, \, to include quotes within a string. This is known as escaping a character. See the Microsoft Documentation for more escape characters sequences.

Example

Console.WriteLine("\"The dog's favorite toy is a stuffed hedgehog,\" said Chris");

Console Output

"The dog's favorite toy is a stuffed hedgehog," said Chris

7.7.1. Check Your Understanding

Question

Which of the options below prints 'Launch' and 'Code' on separate lines?

  1. Console.WriteLine("Launch\nCode");
  2. Console.WriteLine("Launch/nCode");
  3. Console.WriteLine("Launch" + "Code");
  4. Console.WriteLine("Launch\tCode");
  5. Console.WriteLine("Launch/tCode");