Search code examples
javajava.util.scannerreplaceall

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


Solution

  • try this :

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

    OR

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