Java Program 10: Replace All Occurrence Of Sub string In Given String

Hello folks,

In this post, we will learn how to replace a sub string in a given string. Detailed description of problem is given below:
Problem:

You have an input string and you need to replace sub string from new sub string in given input string.

Example:

Input: This bike is my bike.
Action: Replace “bike” from “car.
output: This car is my car.

Logic:

  1. We will use split method and will split given input string from word which needs to be replaced. Remember, how split works.
  2. After split, add new word at end of all split word except last one.
  3. First verify if last word in input string is equal to string to be replaced. If yes then append new word.

Solution:

package MakeSeleniumEasy;

import java.util.Scanner;

public class ReplaceString 
{
    public static void main(String[] args)
    {
    	
    	Scanner sc= new Scanner(System.in);
		System.out.println("Enter string:");
		String inputString= sc.nextLine();
		System.out.println("Enter word to be replaced from:");
		String from= sc.nextLine();
		System.out.println("Enter word to replaced to:");
		String to= sc.nextLine();
		System.out.println("Input string: "+inputString);
		System.out.println("Word to be replaced from: "+from);
		System.out.println("Word to be replaced to: "+to);
        String replacedString = replaceMethod(inputString, from, to);
        System.out.println(replacedString);
    }

    static String replaceMethod(String str, String from, String to) 
    {
    	// We will split string array using wordToBeReplaced. Splitter word will not be stored.
        String[] arr = str.split(from);
        StringBuilder output = new StringBuilder();

        //Concatenating new word in last of word of each index except last index
        // We can not add new word for last indexed word as we are not sure we need to add or not.
        int i = 0;
        for (; i < arr.length - 1; i++)
        {	
        	output.append(arr[i]).append(to);
        }

        output.append(arr[i]);
        
        
        // Verifying if last word of given string is similar to word to be replaced/
        // If yes, then append new word otherwise don't. 
        if(str.substring((str.length()-from.length()),str.length()).equals(from))
        {
        	output.append(to);
        }

        return output.toString();
    }
    
    
    
}

Output:

Enter string:
this car is my car
Enter word to be replaced from:
car
Enter word to replaced to:
bike
Input string: this car is my car
Word to be replaced from: car
Word to be replaced to: bike
this bike is my bike
============================
Enter string:
thiscarismycar
Enter word to be replaced from:
car
Enter word to replaced to:
bike
Input string: thiscarismycar
Word to be replaced from: car
Word to be replaced to: bike
thisbikeismybike

I have put comments wherever it is necessary. If you have any doubt, you can ask me.

#HappyCoding

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 4+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went throw so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning