Victor
Victor

Reputation: 17097

Java replace special characters in a string

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.

Upvotes: 1

Views: 2954

Answers (7)

CoolBeans
CoolBeans

Reputation: 20800

Try str.replaceAll("\\\\n", ""); - this is called double escaping :)

Upvotes: 2

Bart Kiers
Bart Kiers

Reputation: 170158

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,}", " ")

Upvotes: 1

Jinjavacoder
Jinjavacoder

Reputation: 265

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

Upvotes: 0

Prabath Siriwardena
Prabath Siriwardena

Reputation: 5921

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("  ", " ");
}

Upvotes: 1

Andrew Black
Andrew Black

Reputation: 79

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...

Upvotes: 0

Michael Easter
Michael Easter

Reputation: 24468

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.

Upvotes: 1

Tristan
Tristan

Reputation: 9121

Sure, the standard API will work, but you may have to double escape ("\\n").

Upvotes: 0

Related Questions