Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

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

Code in Java

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);
   }
}
This code is contributed by Shubham Nigam (Prepinsta Placement Cell Student)

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