Java Program to Replace Substring in a String

Replace substring in a string

In this article we are going to make a java program to replace substring in a string . we will be asking the user to input a base string, than we will ask for a substring which is to replaced, and finally we will ask for the string which is to be placed on the place of substring and by using replaceAll() we will replace old string with new one.

Java Program to Replace Substring in a String

Algorithm

  •  Take a string input from user and store it in a variable called “s1” 
  • After that take a string input from user to replace string and store it in a variable called as “oldString” 
  • Take new string input from user to replace that old string with new String and store this value in a variable called as “newString”
  • After that user replace() method to replace old string with new string

Java (Replace Substring in a String Java)

//Replace Substring in a String Java code
import java.util.Scanner; public class ReplaceASubstringInAString { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter a String : "); String s1 = sc.nextLine(); System.out.print("Enter the String to be replaced : "); String oldString = sc.nextLine(); System.out.print("Enter the new String : "); String newString =sc.nextLine(); String replaceString = s1.replace(oldString, newString); System.out.println("New String is :"+replaceString); } }

Output

Enter a String : prepinsta
Enter the String to be replaced : insta
Enter the new String : insta is good
New String is :prepinsta is good