String str1 = "The rumour is that the neighbours displayed good behaviour by labouring to help Mike because he is favoured.";
str1.replaceAll("our", "or");
System.out.println(str1);
String str1 = "The rumour is that the neighbours displayed good behaviour by labouring to help Mike because he is favoured.";
str1.replaceAll("our", "or");
System.out.println(str1);
Method replaceAll
returns a new string where each occurrence of the matching substring is replaced with the replacement string.
Your code doesn't work because String
is immutable. So, str1.replaceAll("our", "or");
doesn't change str1
.
Try this code:
String str1 = "I am trying to replace the pattern.";
String str2 = str1.replaceAll("replace", "change");
System.out.println(str2);
If you don't what str2
, try this code:
String str1 = "I am trying to replace the pattern.";
System.out.println(str1.replaceAll("replace", "change"));
And read about Immutability of Strings in Java.