Check if string contains \n Java

前端 未结 4 452
别那么骄傲
别那么骄傲 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
     .
    
    0 讨论(0)
  • 2020-12-10 02:06

    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.

    0 讨论(0)
  • 2020-12-10 02:07

    The second one:

    word.contains("\n");
    
    0 讨论(0)
  • 2020-12-10 02:14

    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;
        }
    
    0 讨论(0)
提交回复
热议问题