Roshan
Roshan

Reputation: 2059

How to identify that the given string ends with newline or not

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

Upvotes: 2

Views: 8235

Answers (5)

bugs_
bugs_

Reputation: 3744

If you want know system new line separator:

System.getProperty("line.separator")

and :

function String.endsWith()

Upvotes: 5

ninjalj
ninjalj

Reputation: 43748

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

Upvotes: 1

developer
developer

Reputation: 9478

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

Upvotes: 0

Kamahire
Kamahire

Reputation: 2209

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

Upvotes: -1

Michael
Michael

Reputation: 12826

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. :)

Upvotes: 0

Related Questions