Java replace special characters in a string
Question
I have a string like this:
BEGIN\n\n\n\nTHIS IS A STRING\n\nEND
And I want to remove all the new line characters and have the result as :
BEGIN THIS IS A STRING END
How do i accomplish this? The standard API functions will not work because of the escape sequence in my experience.
Solution
A simple replace('\n', ' ')
will cause the string to become:
BEGIN THIS IS A STRING END
**** **
where the *
's are spaces. If you want single spaces, try replaceAll("[\r\n]{2,}", " ")
And in case they're no line breaks but literal "\n"
's wither try:
replace("\\n", " ")
or:
replaceAll("(\\\\n){2,}", " ")
OTHER TIPS
Try str.replaceAll("\\\\n", "");
- this is called double escaping :)
This works for me:
String s = "BEGIN\n\n\n\nTHIS IS A STRING\n\nEND";
String t = s.replaceAll("[\n]+", " ");
System.out.println(t);
The key is the reg-ex.
String str = "BEGIN\n\n\n\nTHIS IS A STRING\n\nEND;";
str = str.replaceAll("\\\n", " ");
// Remove extra white spaces
while (str.indexOf(" ") > 0) {
str = str.replaceAll(" ", " ");
}
Sure, the standard API will work, but you may have to double escape ("\\n").
I don't usually code in Java, but a quick search leads me to believe that String.trim should work for you. It says that it removes leading and trailing white space along with \n \t etc...
Hope this snippet will help,
Scanner sc = new Scanner(new StringReader("BEGIN\n\n\n\nTHIS IS A STRING\n\nEND "));
String out = "";
while (sc.hasNext()) {
out += sc.next() + " ";
}
System.out.println(out);