Problem Statement : To search and replace a pattern of string with another.
Algorithm
1) Start.
2) Initialize the three strings s1,s2,and s3.
3) Read the string.
4) Enter the pattern to be searched.
5) Check whether the given pattern in the string using
6) s1.substring(s2).
7) Replace the pattern with another string using
8) s1=s1.concat(s2).
9) Print the result.
10) Stop.
Program
import java.io.*; public class StrDemo { public static void main(String args[]) { DataInputStream in= new DataInputStream(System.in); String str,chstr,repstr,newstr="",substr=""; int len,chlen,idx=0; try { System.out.println("\nEnter the string : "); str=in.readLine(); len=str.length(); System.out.println("\nEnter the sub string to be replaced : "); chstr=in.readLine(); chlen=chstr.length(); System.out.println("\nEnter the new sub string : "); repstr=in.readLine(); while(len>idx) { if(idx+chlen <= len) { substr=str.substring(idx,idx+chlen); if(substr.compareTo(chstr)==0) { newstr=newstr.concat(repstr); idx+=chlen; } else { newstr=newstr.concat(substr.substring(0,1)); idx+=1; } } else { newstr=newstr.concat(str.substring(idx,len)); break; } } System.out.println("\nThe resulting string is : " + newstr); } catch(Exception e) { System.out.println("Error : " + e); } } } |
Output
Enter the string :
abcdabccabda
Enter the sub string to be replaced :
ab
Enter the new sub string :
ka
The resulting string is : kacdkacckada