公告
财富商城
积分规则
提问
发文
2020-02-05 07:16发布
来,给爷笑一个
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 .
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; }
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.
"\n"
The second one:
word.contains("\n");
最多设置5个标签!
If the string was constructed in the same program, I would recommend using this:
But if you are specced to use \n, this driver illustrates what to do:
Resulted in
In reponse to your comment:
Results in
I'd rather trust JDK over System property. Following is a working snippet.
For portability, you really should do something like this:
unless you're absolutely certain that
"\n"
is what you want.The second one: