Make Selenium Easy

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:

Output:

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

#HappyCoding

Table of Contents

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Currently getting paid in American Dollars. Writing technical posts and creating YouTube videos are my hobbies.

2 thoughts on “Java Program 10: Replace All Occurrence Of Sub string In Given String

  1. public class ReplaceAllDemo {
    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);

    inputString = inputString.replaceAll(from, to);
    System.out.println(inputString);
    }
    }

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.

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

by Amod Mahajan time to read: 2 min
2
%d bloggers like this: