UPDATED:
I changed it to work with multiple appearances \ n. Please note that this may not be very effective.
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 index 0.
source share