检查字符串是否包含\ n Java [英] Check if string contains \n Java

查看:209
本文介绍了检查字符串是否包含\ n Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查字符串是否包含\ n或换行符?

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

word.contains("\\n")
word.contains("\n")


推荐答案

如果字符串是在同一个程序中构建的,我建议使用它:

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);

但是如果你打算使用\ n,这个驱动程序说明了该怎么做:

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"));

    }

}

导致

true
false
false
false

在回复你的评论时:

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);

    }

}

结果

6
test
.
7
test
 .

这篇关于检查字符串是否包含\ n Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆