27

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

word.contains("\\n")
word.contains("\n")
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
Pit Digger
  • 9,618
  • 23
  • 78
  • 122

4 Answers4

47

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
 .
corsiKa
  • 81,495
  • 25
  • 153
  • 204
11

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.

Amir Afghani
  • 37,814
  • 16
  • 84
  • 124
8

The second one:

word.contains("\n");
krock
  • 28,904
  • 13
  • 79
  • 85
  • 1
    could you clarify why it doesn't work. What is your input, what is the result and what is the expected result? – Kris Babic Apr 01 '11 at 20:30
  • Sorry about that I had not restarted my tomcat after rebuilding JAr so it didnt make effect.It works now although Replace s = s.replace("\n", " \n "); is not working . – Pit Digger Apr 01 '11 at 20:49
1

I'd rather trust JDK over System property. Following is a working snippet.

    private boolean checkIfStringContainsNewLineCharacters(String str){
        if(!StringUtils.isEmpty(str)){
            Scanner scanner = new Scanner(str);
            scanner.nextLine();
            boolean hasNextLine =  scanner.hasNextLine();
            scanner.close();
            return hasNextLine;
        }
        return false;
    }
Arjit
  • 421
  • 7
  • 20