×
FREE ASSISTANCE FOR THE INQUISITIVE PEOPLE
Tutorial Topics
X
softetechnologies
What are classes and objects in java.
Write a programme in java to accept a string and replace all CAT into DOG - Java
6500    Arnab De    16/06/2018

Write a programme in java to accept a string and replace all "CAT" into "DOG".

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.

softetechnologies
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);
    }
}
softetechnologies

Output
Enter A String : I HAVE A CAT. DO YOU WANT THAT CAT
I HAVE A DOG. DO YOU WANT THAT DOG

Another way of solution for the same program

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());
    }
}
What are classes and objects in java.
softetechnologies
Author Details
Arnab De
I have over 16 years of experience working as an IT professional, ranging from teaching at my own institute to being a computer faculty at different leading institute across Kolkata. I also work as a web developer and designer, having worked for renowned companies and brand. Through tutorialathome, I wish to share my years of knowledge with the readers.
Enter New Comment
Comment History
No Comment Found Yet.
Rabindranath Tagore
Everything comes to us if we create the capacity to receive it.
Rabindranath Tagore
3854
75.03
Today So Far
Total View (Lakh)
softetechnologies
26/05/2018     52291
25/06/2018     44059
01/01/2018     42982
28/06/2017     40718
02/08/2017     39573
01/08/2017     33742
06/07/2017     33559
15/05/2017     32837
14/07/2017     29127
11/09/2018     29120
softetechnologies