What is the difference between \r\n, \r, and \n?

String

String Problem Overview


What is difference in a string between \r\n, \r and \n? How is a string affected by each?

I have to replace the occurrences of \r\n and \r with \n, but I cannot get how are they different in a string...

I know that \r is like hitting enter and \n is for a new line.

String Solutions


Solution 1 - String

  • \r = CR (Carriage Return) → Used as a new line character in Mac OS before X
  • \n = LF (Line Feed) → Used as a new line character in Unix/Mac OS X
  • \r\n = CR + LF → Used as a new line character in Windows

Solution 2 - String

All 3 of them represent the end of a line. But...

  • \r (Carriage Return) → moves the cursor to the beginning of the line without advancing to the next line
  • \n (Line Feed) → moves the cursor down to the next line without returning to the beginning of the line — In a *nix environment \n moves to the beginning of the line.
  • \r\n (End Of Line) → a combination of \r and \n

Solution 3 - String

They are normal symbols as 'a' or 'ю' or any other. Just (invisible) entries in a string. \r moves cursor to the beginning of the line. \n goes one line down.

As for your replacement, you haven't specified what language you're using, so here's the sketch:

someString.replace("\r\n", "\n").replace("\r", "\n")

Solution 4 - String

A carriage return (\r) makes the cursor jump to the first column (begin of the line) while the newline (\n) jumps to the next line and might also to the beginning of that line. So to be sure to be at the first position within the next line one uses both.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHaya RaedView Question on Stackoverflow
Solution 1 - StringTom BowenView Answer on Stackoverflow
Solution 2 - StringExasmView Answer on Stackoverflow
Solution 3 - StringdurilkaView Answer on Stackoverflow
Solution 4 - StringMattenView Answer on Stackoverflow