检查字符串是否包含\ n Java

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

word.contains("\\n")

word.contains("\n")

回答:

如果字符串是在同一程序中构造的,则建议使用以下命令:

String newline = System.getProperty("line.separator");

boolean hasNewline = word.contains(newline);

但是,如果您指定使用\ n,则此驱动程序说明了如何做:

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 的全部内容, 来源链接: utcz.com/qa/430325.html

回到顶部