While working with different languages and operating systems, we often encounter general questions on \r and \n and their difference. In this article, let’s discuss what \r and \n and \n\r combined are.
Differentiate between \r and \n and \n\r
- \n stands for new-line – \n will move the cursor down to a new line
- \r stands for carriage return
Both \n and \r are different characters and were used as end of line terminators in different operating systems.
- \n – is the end-of-line terminator for text files in Unix
- \r – was previously used as the end-of-line terminator in Mac text files, now \n is also used.
- \n\r -are used to terminate lines in the DOS and Windows text files.
Example Demonstration with MAC
The \r moves to the current line’s right, without moving to the next line while \n will move to the start of the next line .Â
Here, in the below example we are using javascript language for demonstration purposes and the below code is compiled, run in node.js
Using \r
let stringVar = "hello\r" for(let i=0;i < 3;i++) { console.log(stringVar); }
Output:-
hello hello hello
Using \n
Frequently Asked:
- How not to use Smart Pointers in C++?
- Python- Find the largest file in a directory
- Python: Get list of all timezones in pytz module
- Using std::find & std::find_if with User Defined Classes
let stringVar = "hello\n" for(let i=0;i < 3;i++) { console.log(stringVar); }
Output:-
hello hello hello
Using \n\r
let stringVar = "hello\n\r" for(let i=0;i < 3;i++) { console.log(stringVar); }
Output:-
hello hello hello
Note that the output is same as with \n.
Example Demonstration with LINUX
Using \r
let stringVar = "hello\r" for(let i=0;i < 3;i++) { console.log(stringVar); }
Output:-
hello hello hello
We are getting different output than the output for \r using node.js in MAC.
Using \n
let stringVar = "hello\n" for(let i=0;i < 3;i++) { console.log(stringVar); }
Output:-
hello hello hello
Using \n\r
let stringVar = "hello\n\r" for(let i=0;i < 3;i++) { console.log(stringVar); }
Output:-
hello hello hello
Note that we are getting two line breaks instead of one.
I hope this article helped you to understand the difference between \n, \r and \n\r. Good Luck !!!