This is a very easy programme. Just create a object of Scanner class and read a string. Now use the replace() method of the String class. This methods have two parameters. First parameter is the search word. i.e. this word is search from the given text and replace by the second parameter. Here CAT of the text is replace by the DOG. Now print the resultant String.
import java.util.*; public class CatDog { public static void main(String []args) { Scanner sc=new Scanner(System.in); System.out.print("Enter A String : "); String str=sc.nextLine(); str=str.replace("CAT","DOG"); System.out.print(str); } }
Output
Enter A String : I HAVE A CAT. DO YOU WANT THAT CAT
I HAVE A DOG. DO YOU WANT THAT DOG
import java.util.*; public class Replace { public static void main(String []args) { Scanner sc=new Scanner(System.in); System.out.print("Enter A String : "); String str=sc.nextLine(); String words[]=str.split(" "); String res=""; for(int i=0; i<words.length;i++) { if(words[i].equals("CAT")) { res += "DOG "; } else { res += words[i] + " "; } } System.out.print(res.trim()); } }