1public static void main(String args[]){
2String s1="my name is khan my name is java";
3String replaceString=s1.replace("is","was");//replaces all occurrences of "is" to "was"
4System.out.println(replaceString);
5}}
6
1String s = "new String";
2String replaced = s.replace("new","Test");
3 ^ ^
4 old new char
1String str = in.nextLine(); //Original String
2char cr = in.next().charAt(0); // character to replace
3int index = in.nextInt(); // Index where replaced
4str = str.substring(0, index) + cr + str.substring(index + 1);// modified string
5
1// We want to replace every # with a 8
2String larry = "Larry is # years old";
3String newString = larry.replace("#", "8");
1String str = "..............................";
2
3 int index = 5;
4
5 char ch = '|';
6
7 StringBuilder string = new StringBuilder(str);
8 string.setCharAt(index, ch);
9
10 System.out.println(string);
1public class JavaExample{
2 public static void main(String args[]){
3 String str = new String("Site is BeginnersBook.com");
4
5 System.out.print("String after replacing com with net :" );
6 System.out.println(str.replaceFirst("com", "net"));
7
8 System.out.print("String after replacing Site name:" );
9 System.out.println(str.replaceFirst("Beginners(.*)", "XYZ.com"));
10 }
11}