Write a program to accept a string and replace all occurrence of char by another string. Example => i/p s1 => welcome search =>e replace => ZZ o/p => wZZlcomZZ

import java.util.*;
class StringReplace
{
String str,search,rep;
       //To accept strings
StringReplace()
{
Scanner s=new Scanner(System.in);
System.out.print("Enter string your string := ");
str=s.next();  //next() method finds and returns the next complete token from this scanner.
System.out.print("Enter search string := ");
search=s.next(); //next() method finds and returns the next complete token from this scanner.
System.out.print("Enter replace string := ");
rep=s.next();  //next() method finds and returns the next complete token from this scanner.
}
        //To search and replace chars in string
void replace()
{
String s1="";
int s;
while(true)
{
s=str.indexOf(search);
if(s==-1)
{
System.out.println("Not found");
break;
}
else
{
s1=s1+str.substring(0,s)+rep;
str=str.substring(s+1);
}
}
System.out.println("Replace string is : "+s1);
}
}

//To create object 
class TestStringReplace
{
public static void main(String args[])
{
StringReplace obj=new StringReplace();
obj.replace();
}
}

0 Comments