Friday, January 11, 2013

Escape Characters in C#.NET


Like in other C-based languages, in C# string literals may contain various escape characters, which qualify how the character data should be printed to the output stream. Each escape character begins
with a backslash, followed by a specific token. In case you are a bit rusty on the meanings behind

these escape characters, lists the more common options.

\'  Inserts a single quote into a string literal.

\"  Inserts a double quote into a string literal.

\\  Inserts a backslash into a string literal. This can be quite helpful when defining file paths.

\a  Triggers a system alert (beep). For console applications, this can be an audio clue to the user.

\n  Inserts a new line (on Win32 platforms).

\r  Inserts a carriage return.

\t  Inserts a horizontal tab into the string literal.

For example, to print a string that contains a tab between each word, you can make use of the \t escape character:

// Literal strings may contain any number of escape characters. 

string s3 = "Hello\tThere\tAgain";
Console.WriteLine(s3);

As another example, assume you wish to create a string literal that contains quotation marks, another that defines a directory path, and a final string literal that inserts three blank lines after printing the character data. To do so without compiler errors, you would need to make use of the \",

\\, and \n escape characters:

Console.WriteLine("Everyone loves \"Hello World\"");
Console.WriteLine("C:\\MyApp\\bin\\debug");
Console.WriteLine("All finished.\n\n\n");

No comments:
Write comments
Recommended Posts × +