In programming languages if I use "\n" it adds a newline character.
Could somebody explain how the "\n" gets translated to a newline and the same for "\t"?
But what is \n exactly? The newline character ( \n ) is called an escape sequence, and it forces the cursor to change its position to the beginning of the next line on the screen. This results in a new line.
The \n character matches newline characters.
Adding Newline Characters in a String In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.
A newline (line feed) character \n [Unix and Linux systems] A carriage-return character \r [older Apple computers] A carriage-return character followed immediately by a newline character \r\n [Microsoft systems] A next-line character \u0085 [Unicode text files] A line-separator character \u2028 [Unicode text files]
When the compiler is reading your program and it sees backslash something
it knows to 'pretend' it saw something else. You can imagine that part of the compiler works like this:
current_character = getNextCharacter();
if (current_character == BACKSLASH) {
current_character = getNextCharacter();
if (current_character == 'n') {
/*oh, they want a newline */
} else if (current_character == 't') {
/* it's a tab they want */
} else /* ... and so on and so forth */
}
Assuming we talk about strings inside the language, such as "Hello,\tWorld\n"
, then it's the compilers job to detect a backslash, and then insert the appropriate character sequence for newline and tab on that machine into the string in the generated executable file.
The code to deal with this in the compiler is fairly complex, because there is a huge amount of OTHER things to bear in mind when parsing the code, but if we simplify it a bit:
if (inQuote) // So inside ' or "
{
if (currentChar == '\')
{
switch(nextChar)
{
case 'n':
InsertNewLine();
break;
case 't':
InsertTab();
break;
case 'b':
InsertBackSpace();
break;
... several more of these ...
case '\': // '\\' outputs one '\'
InsertBackSlash();
break;
default:
Insert(nextChar); // Ignore any others.
break;
}
}
}
I've cheated and made functions for InsertXX
, where in reality, it's probably just a *output++ = 10;
or *output++ = 9;
[or some defined constant that translates to the same].
The \ character is in many languages an 'escape character'. With that character you can add special non printable characters, such as new line or tab, but also quotes. If you need to use " to delimit a string, you can use \" to print a quote mark within it.
for the windows command prompt, ^ works similar for printing special characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With