user1217222
user1217222

Reputation: 67

Forcing newline to print correctly again

I had to export a bunch of strings to a CSV that I opened in excel. The strings contained '\n' and '\t' which I needed included in the CSV so I did the following before exporting the data:

public static String unEscapString(String s)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.length(); i++)
    {
        switch (s.charAt(i))
        {
            case '\n': sb.append("\\n"); break;
            case '\t': sb.append("\\t"); break;
            default: sb.append(s.charAt(i));
        }
    }
    return sb.toString();
}

The problem is that I am now reimporting the data into Java but I can't figure out how to get the newline and tab to print correctly again. I've tried:

s.replaceAll("\\n", "\n");

but it still ignores the newlines. Help?

EDIT: Example of what i'm trying to do:

Say one string in the CSV is "foo \n bar". When I import it using Java and i'm trying to print the same string to the console but have the newline behave correctly

Upvotes: 0

Views: 71

Answers (3)

jpmc26
jpmc26

Reputation: 29974

replaceAll's first argument is a regular expression. You have 2 choices. You can use plain old replace like so:

s.replace("\\n", "\n");

or you can escape the slash for the regex parser (which is stripping the single slash out):

s.replaceAll("\\\\n", "\n");

or

s.replaceAll(Pattern.quote("\\n"), "\n");

I would opt for replace since you're not using a regular expression.

Upvotes: 2

Joshua Hyatt
Joshua Hyatt

Reputation: 1340

If you want an actual newline in the string, it should be \n, not \\n. The way you have it, it is being interpreted as a backslash and then an 'n'.

Upvotes: 0

herohuyongtao
herohuyongtao

Reputation: 50717

It should be

sb.append("\n"); 

Otherwise, you will get a '\' and a 'n' by using "\\n".


But I recommend you to use:

sb.append(System.getProperty("line.separator"));

Here System.getProperty("line.separator") gives you platform independent newline in java. Also from Java 7 there's a method that returns the value directly: System.lineSeparator().

Upvotes: 1

Related Questions