Check if string contains \n Java

前端 未结 4 467
别那么骄傲
别那么骄傲 2020-12-10 01:18

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

word.contains(\"\\\\n\")
word.contains(\"\\n\")
4条回答
  •  星月不相逢
    2020-12-10 01:49

    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
     .
    

提交回复
热议问题