Replace Substring in Java
Replace all occurrences of a substring in a string.
BeginnerModule 4: String ProgramsExample 13 of 25
replace-substring.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Enter main string: ");7 String s = sc.nextLine();8 System.out.print("Enter substring to replace: ");9 String oldSub = sc.nextLine();10 System.out.print("Enter new substring: ");11 String newSub = sc.nextLine();1213 String result = s.replace(oldSub, newSub);14 System.out.println("Result: " + result);15 sc.close();16 }17}
Output
Enter main string: I like C Enter substring to replace: C Enter new substring: Java Result: I like Java
What's going on
We use String.replace to swap all occurrences of a substring.