How do I check if string contains \n or new line character ?
word.contains("\\n") word.contains("\n")
On the Windows system, it is \r\n , on the Linux system, it is \n . In Java, we can use System. lineSeparator() to get a platform-dependent new line character. P.S The System.
In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.
Java String contains() Method The contains() method checks whether a string contains a sequence of characters. Returns true if the characters exist and false if not.
What does \n mean in Java? This means to insert a new line at this specific point in the text. In the below example, "\n" is used inside the print statement, which indicates that the control is passed to the next line. As a result, the text following "\n" will be printed on the next line.
If the string was constructed in the same program, I would recommend using this:
String newline = System.getProperty("line.separator"); boolean hasNewline = word.contains(newline);
But if you are specced to use \n, this driver illustrates what to do:
class NewLineTest { public static void main(String[] args) { String hasNewline = "this has a newline\n."; String noNewline = "this doesn't"; System.out.println(hasNewline.contains("\n")); System.out.println(hasNewline.contains("\\n")); System.out.println(noNewline.contains("\n")); System.out.println(noNewline.contains("\\n")); } }
Resulted in
true false false false
In reponse to your comment:
class NewLineTest { public static void main(String[] args) { String word = "test\n."; System.out.println(word.length()); System.out.println(word); word = word.replace("\n","\n "); System.out.println(word.length()); System.out.println(word); } }
Results in
6 test . 7 test .
For portability, you really should do something like this:
public static final String NEW_LINE = System.getProperty("line.separator") . . . word.contains(NEW_LINE);
unless you're absolutely certain that "\n"
is what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With