gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:36:24 25 4
gpt4 key购买 nike

如何检查字符串是否包含\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
.

关于java - 检查字符串是否包含\n Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5518451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com