0

I want to replace the \n character with a space. The below code in not working. Any suggestions?

System.out.println("Enter a string:");
    Scanner sc=new Scanner(System.in);
    String str=sc.nextLine().toString();
    //String str="one\ntwo";
    if(str.contains("\\n")){
        System.out.println("yes");
        str=str.replaceAll("\\n", " " );
    }
    System.out.println("str : "+str);

The input string is one\ntwo

Somdutta
  • 193
  • 1
  • 2
  • 9
  • possible duplicate of [replace \n and \r\n with
    in java](http://stackoverflow.com/questions/3056834/replace-n-and-r-n-with-br-in-java)
    – Kick Buttowski Oct 05 '14 at 18:14

3 Answers3

3

replaceAll("\\n", " " ) uses regex as first argument and "\\n" is treated by Java regex engine as \n which represents line separator, not \ and n characters. If you want to replace \n literal (two characters) you either need to

  • escape \ in regex itself by replaceAll("\\\\n", " " );
  • use replace instead of replaceAll which will do escaping for you

Preferred way is using

str = str.replace("\\n", " " );

BTW sc.nextLine() already returns String, so there is no need for

sc.nextLine().toString();
//           ^^^^^^^^^^^ this part is unnecessary 
Community
  • 1
  • 1
Pshemo
  • 113,402
  • 22
  • 170
  • 242
1

try this :

str=str.replaceAll("\\\\n", " " );

OR

 str=str.replace("\\n", " " );
Rustam
  • 6,307
  • 1
  • 21
  • 25
0

Your condition is not good

if(str.contains("\\n")) -> if(str.contains("\n"))

all it describe here : https://stackoverflow.com/a/5518515/4017037

Community
  • 1
  • 1
stacky
  • 715
  • 5
  • 16
  • It seems that OP doesn't have `\n` (line separator) in String, but `"\\n"` ``\`` character followed by `n`. – Pshemo Oct 05 '14 at 18:20