Reputation: 193
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
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
\
in regex itself by replaceAll("\\\\n", " " );
replace
instead of replaceAll
which will do escaping for youPreferred 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
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
Reputation: 6515
try this :
str=str.replaceAll("\\\\n", " " );
OR
str=str.replace("\\n", " " );
Upvotes: 1