Replace Substring
Replace all occurrences of a substring in a string.
BeginnerTopic: Module 4: String Programs
Java Replace Substring Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter main string: ");
String s = sc.nextLine();
System.out.print("Enter substring to replace: ");
String oldSub = sc.nextLine();
System.out.print("Enter new substring: ");
String newSub = sc.nextLine();
String result = s.replace(oldSub, newSub);
System.out.println("Result: " + result);
sc.close();
}
}Output
Enter main string: I like C Enter substring to replace: C Enter new substring: Java Result: I like Java
Understanding Replace Substring
We use String.replace to swap all occurrences of a substring.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.