Page 302 - ComputerScience_Class_11
P. 302
The output of the preceding program is as follows:
BlueJ: Terminal Window - Java
Options
The Extracted string is: New
The replace(char chartoreplace, char chartoinsert) Function
This function replaces all the characters mentioned in ‘chartoreplace’ with the characters given in ‘chartoinsert’ and
creates a new String. The syntax is:
String <variable> = String_datatype_Variable.replace(char chartoreplace, char chartoinsert);
Let us see the below example:
Write a program to replace all occurrences of the character ‘i’ with ‘a’ in the string “Rama is
Program 12
going to play cricket” and display the result.
1 class substring
2 {
3 public static void main(String[] args)
4 {
5 String str= "Rama is going to play cricket";
6 String replacechar= str.replace(‘i’, ‘a’);
7 System.out.println("The replaced string is: " + replacechar);
8 }
9 }
The output of the preceding program is as follows:
BlueJ: Terminal Window - Java
Options
The replaced string is: Rama as goang to play cracket
The replace(String stringtoreplace, String stringtoinsert) Function
This function replaces all the sequence of characters given in ‘stringtoreplace’ with the sequence of characters given
in ‘stringtoinsert’ and creates a new String. It replaces all the sets having the same sequence. The syntax is:
String <variable> = String_datatype_Variable.replace(String stringtoreplace, String
stringtoinsert);
Let us see the below example:
Write a program to replace all occurrences of the word “Morning” with “Evening” in the
Program 13
string and display the result.
1 class stringReplace
2 {
3 public static void main(String[] args)
4 {
300 Touchpad Computer Science (Ver. 3.0)-XI

