Question:
How to replace a word inside a string by a different word ?
Answer:
Using the String replace() method.
Code:
public class ReplaceSubString { public static void main(String[] args) { String str1= "The cat in the hat."; String str2 = str1.replace( "cat","dog" ); System.out.println("Original string: " + str1); System.out.println("New string: " + str2); } }
Output:
$ java ReplaceSubString Original string: The cat in the hat. New string: The dog in the hat.