2

In java how to identify that the provided string ends with newline character or not?

Roshan
  • 2,019
  • 8
  • 36
  • 56

5 Answers5

5

If you want know system new line separator:

System.getProperty("line.separator")

and :

function String.endsWith()
har07
  • 88,338
  • 12
  • 84
  • 137
bugs_
  • 3,544
  • 4
  • 34
  • 39
  • 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
  • 2
    endsWith 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
1

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".

Community
  • 1
  • 1
ninjalj
  • 42,493
  • 9
  • 106
  • 148
0
String superString = "This is a string\n";

if (superString.charAt(superString.length()-1) == "\n")
{
    ...
}

Although, I don't code in Java. But Google is my friend. :)

Michael
  • 11,912
  • 6
  • 49
  • 64
0

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");

developer
  • 9,116
  • 29
  • 91
  • 150
-1

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'.

Kamahire
  • 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