您好,欢迎来到五一七教育网。
搜索
您的当前位置:首页java查看字符串是否有n,检查字符串是否包含\ n Java

java查看字符串是否有n,检查字符串是否包含\ n Java

来源:五一七教育网

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

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

.

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- 517ttc.cn 版权所有 赣ICP备2024042791号-8

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务