Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string contains \n Java

Tags:

How do I check if string contains \n or new line character ?

word.contains("\\n") word.contains("\n") 
like image 861
Pit Digger Avatar asked Apr 01 '11 20:04

Pit Digger


People also ask

How do you identify a new line character in Java?

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.

Can a string contain newline?

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.

How do you check if a string contains a certain character in Java?

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 do in Java string?

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.


2 Answers

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  . 
like image 111
corsiKa Avatar answered Sep 24 '22 09:09

corsiKa


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.

like image 35
Amir Afghani Avatar answered Sep 22 '22 09:09

Amir Afghani