In Java, you can replace part of a string using the replace() method:
s.replace(old, new) // replaces all occurrences
s.replaceFirst(regex, new) // replaces first match
Here are some examples:
String sentence = "I love cats";
String result = sentence.replace("cats", "dogs");
System.out.println(result); // "I love dogs"
String text = "aaa";
System.out.println(text.replace("a", "b")); // "bbb"
replace() returns a new String — the original is not modified.
Assignment
Follow the Coding Tutorial and replace "cats" with "dogs" in sentence!
Hint
Use sentence.replace("cats", "dogs") and assign it to result.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
