I am looking for a proper and robust way to find and replace all newline
or breakline
chars from a String
independent of any OS platform with
.
This is what I tried, but didn't really work well.
public static String replaceNewLineChar(String str) {
try {
if (!str.isEmpty()) {
return str.replaceAll("
", "\n")
.replaceAll("
", "\n")
.replaceAll(System.lineSeparator(), "\n");
}
return str;
} catch (Exception e) {
// Log this exception
return str;
}
}
Example:
Input String:
This is a String
and all newline chars
should be replaced in this example.
Expected Output String:
This is a String
and all newline chars
should be replaced in this example.
However, it returned the same input String back. Like it placed
and interpreted it as Newline again.
Please note, if you wonder why would someone want
in there, this is a special requirement by user to place the String in XML afterwords.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…