Somdutta
Somdutta

Reputation: 193

replaceAll () function Scanner in Java

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

Upvotes: 0

Views: 1904

Answers (3)

Pshemo
Pshemo

Reputation: 124225

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 

Upvotes: 3

stacky
stacky

Reputation: 820

Your condition is not good

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

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

Upvotes: 0

Rustam
Rustam

Reputation: 6515

try this :

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

OR

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

Upvotes: 1

Related Questions