Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Testing if a String ends with a newline

Tags:

java

string

I want to perform a substring.equals("\n"). In the code below, I take the last character and check if it is a newline.

String substring = nextResult.length() > 1 ? nextResult.substring(nextResult.length() - 1) : nextResult;            
return substring.equals("\n") ?  /* do stuff */ : /* do other stuff */;

I take only the last character because Java takes \n as one char. However, from what I see, substring.equals("\n") returns true for whitespaces (" "), and I think tabs (\t). Is that so?

How can I correctly check if the end of a string is a newline, or at least if the string is a newline?

like image 870
Diolor Avatar asked Sep 15 '25 05:09

Diolor


1 Answers

You may use String#endsWith:

boolean endsWithNewline = nextResult.endsWith("\n");

Or String#charAt:

boolean endsWithNewLine = nextResult.charAt(nextResult.length() - 1) == '\n';

However, your current code works fine for me. Perhaps there is some kind of typo in your inputs.

like image 183
bcsb1001 Avatar answered Sep 17 '25 20:09

bcsb1001