Reputation: 845
the newline symbol \n is causing me a bit of trouble when i try to detect and replace it: This works fine:
String x = "Bob was a bob \\n";
String y = x.replaceAll("was", "bob");
System.out.println(y);
butt this code does not give the desired result
String x = "Bob was a bob \\n";
String y = x.replaceAll("\n", "bob");
System.out.println(y);
Upvotes: 4
Views: 20420
Reputation: 396
String x = "Bob was a bob \\n";
String y = x.replaceAll("was", "bob");
System.out.println(y);
one problem here: "\n" is not newline symbol. It should be:
String x = "Bob was a bob \n";// \n is newline symbol, on window newline is \r\n
Upvotes: 1
Reputation: 10117
UPDATED:
I have modified it to work with multiple ocurrences of \n. Note that this may not be very efficient.
public static String replaceBob(String str,int index){
char arr[] = str.toCharArray();
for(int i=index; i<arr.length; i++){
if( arr[i]=='\\' && i<arr.length && arr[i+1]=='n' ){
String temp = str.substring(0, i)+"bob";
String temp2 = str.substring(i+2,str.length());
str = temp + temp2;
str = replaceBob(str,i+2);
break;
}
}
return str;
}
I tried with this and it worked
String x = "Bob was a bob \\n 123 \\n aaa \\n";
System.out.println("result:"+replaceBob(x, 0));
The first time you call the function use an index of 0.
Upvotes: -3
Reputation: 20800
This works as expected.
String str = "A B \n C";
String newStr = str.replaceAll("\\n","Y");
System.out.println(newStr);
Prints:-
A B Y C
Upvotes: 3
Reputation: 586
Your input string does not contain a new line. Instead it contains "\n". See the corrected input string below.
String x = "Bob was a bob \n";
String y = x.replaceAll("\n", "bob");
System.out.println(y);
Upvotes: 0
Reputation: 44181
"Bob was a bob \\n"
becomes literally Bob was a bob \n
There is no newline to replace in the input string. Are you trying to replace a newline character or the escape sequence \\n
?
Upvotes: 8
Reputation: 26860
Did you try this?:
x.replaceAll("\\n", "bob");
You should escape the new line char before using it in replace function.
Upvotes: 0