In java how to identify that the provided string ends with newline character or not?
5 Answers
If you want know system new line separator:
System.getProperty("line.separator")
and :
function String.endsWith()
-
newline may be \n(unix) or \r\n(Windows). Shal i go with this... string.endsWith(\\r?\\n) – Roshan May 12 '11 at 06:33
-
2endsWith doesn't accept regex so no. it should be string.endsWith(System.getProperty("line.separator")) (you might wanna cashe the line separator so you don't keep calling the getProperty each time) – ratchet freak May 12 '11 at 06:44
A newline is an OS-dependant concept. On Unix it's one character (linefeed - U+000A), on Windows it's two characters (carriage return + linefeed, U+000D U+000A), it could be ven the newline character (NEL, U+0085, which I think may be used by some mainframes).
Some regular expression engines accept \R
to mean a newline. Tom Christiansen defines \R
for Java as the following:
\R => (?:(?>\u000D\u000A)|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029])
at this answer.
Then, you would use a regex like \R$
, or, in Java \\R$
, to mean "ends in newline".
String have method call public boolean endsWith(String suffix)
so by using above method we can find the new line character
string.public boolean endsWith("\n");

- 9,116
- 29
- 91
- 150
You need to convert the string in UTF-8 format if it is not there. There using characterAT (), last two character with '\n' and '\r'.

- 2,149
- 3
- 21
- 50
-
Strings in java are encoding independent (its internally represented as UTF-16, but you needn't to care about it, java do it for you) – bugs_ May 12 '11 at 06:29
-
@bugs_ i know in java strings by default UTF-16 but you can format the String s = "some text here"; byte[] b = s.getBytes("UTF-8"); and then you can find out. – Kamahire May 12 '11 at 06:35