OneBite.Dev - Coding blog in a bite size

replace a substring within a string in java

Code snippet on how to replace a substring within a string in java

String str = "My cat is cute";
String newStr = str.replace("cat", "dog");
System.out.println(newStr);

This code replaces the word “cat” with the word “dog” in the string, “My cat is cute”, to generate a new string.

The first line creates a variable, str, and assigns it the value of the string, “My cat is cute”. The second line creates another variable, newStr, and sets the value equal to the result of the function str.replace, which replaces the text “cat” with the text “dog”. The final line prints out the new string to the console. The output would be “My dog is cute”.

java