Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Sometimes, we need characters in a string that are hard to represent in program code. Escape sequences can help.
Before we move on from strings, we should take a moment to look at something called escape sequences. We won't be using these in the cat food store, but you'll definitely need to use them in other programs.
- Sometimes, we need characters in a string that are hard to represent in program code.
- The first line of code is supposed to print a string that includes a newline character, but we get a "Newline in constant" error when we try to run the code.
- We want the "new paragraph" line to include a tab character to indent some text, but when I pressed the Tab key, my editor inserted space characters instead.
- And we're getting more errors from the line that includes a quotation. It's supposed to be a single string that contains double quote marks, but what we wind up with is a a string containing
"He said, "
, code referring to a nonexistent value namedWhoa
, and a second, empty string at the end.
static void Main(string[] args)
{
Console.WriteLine("first line
second line");
Console.WriteLine(" new paragraph");
Console.WriteLine("He said, "Whoa."");
}
Escape sequences let you include characters in strings that might otherwise be hard to represent in code.
Newline: \n
skips to a
new line
Tab: \t
Indents text
Double-quotes: \"
Inserts "double quotes"
Backslash: \\
Inserts a \ backslash
- Let's update the previous program to use escape sequences for the hard-to-represent characters.
static void Main(string[] args)
{
Console.WriteLine("first line\nsecond line");
Console.WriteLine("\tnew paragraph");
Console.WriteLine("He said, \"Whoa.\"");
Console.WriteLine("A backslash: \\");
}
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up