Friday, April 19, 2024 22:08

Table of contents >> Introduction > Escape sequences

Escape sequences

There are times when you want to use special characters or strings that contain special characters, like new line. Obviously, just writing the line on a new line in your code will not do the trick. This is where escape sequences come in handy.

Escape sequences are basically special characters that cannot be represented directly in the source code, and they are all preceded by the backslash character.

The following list will present the most frequently used escape characters:

Here we will declare a string variable, that can hold text, to illustrate the usage of the new line escape sequence:

The above example will not work, and the compiler will warn us about “Newline in constant”. So, how do we add a new line in our string?

The above text will compile successfully, but unfortunately, your text will still be displayed on a single line:

escape sequences

The correct way of adding a new line is to actually use the escape sequence for adding a newline character:

This time, the output will be:

escape sequences

As you can see, our string variable contains the \n escape sequence, which tells the compiler to add a new line character at that location.

Another good example would be the usage of quotation marks. Since the compiler uses the quotation marks to understand where a string variable value begins and ends, adding quotation marks inside our string will make it believe that we meant to end the string value:

The above example will simply generate a compiler error. Instead, the correct form would be:

which will produce this output:

escape sequences

The concepts explained in this lesson are also shown visually as part of the following video:

EXERCISES
1. Declare two variables of type string and assign them a value “The “use” of quotations causes difficulties.” (without the outer quotes). In one of the variables use quoted string and in the other do not use it.

Solution


It is necessary to use the escaping character \” or verbatim strings.

2. Write a program that prints on the console isosceles triangle which sides consist of the copyright character “©”

Solution


Use Console.WriteLine(…), the character © and spaces. Use Windows Character Map in order to find the Unicode code of the sign “©”. Note that the console may display “c” instead of “©” if it does not support Unicode. If this happens, you might be unable to do anything to fix it. Some versions of Windows just do not support Unicode in the console even when you explicitly set the character encoding to UTF-8:
You may need to change the font of your console to some font that supports the “©” symbol, e.g. “Consolas” or “Lucida Console”.

Tags:

Leave a Reply



Follow the white rabbit