replace( char oldch, char newch) in JAVA – JAVA 10th Class notes – ICSE JAVA Notes

replace( char oldch, char newch)  in JAVA – JAVA 10th Class notes – ICSE JAVA Notes

 

replace( char oldch, char newch) :

replace( char oldch, char newch) function replaces all the occurrences of the specified old character with the new character within the given String.

 

Syntax : String res=str.replace (oldch, newch);

 

Example : String str= “Sim”

String res=str.replace(‘ i’, ‘a’);

 

Output : Sam

 

Example : String str = “ The green bottle is in green bag.”

String res=str.replace(“green”, “red”);

 

Output : The red bottle is in red bag.

 

/* Program to illustrate the function replace() */

 

import java.io.*;

class Replace

{

public static void main(String args[])throws IOException

{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.print(” Enter a String : “);

String str=br.readLine();

System.out.print(” Enter a Charcater to be Replaced :”);

char oldch=(char)br.read();

char a=(char)br.read();

System.out.print(” Enter New Charcater :”);

char newch=(char)br.read();

String res=str.replace(oldch,newch);

System.out.println(” New String is : ” + res);

}

}

Leave a Reply

Your email address will not be published. Required fields are marked *

Security Code: