Java program to replace one string with another string

In this Java tutorial, I’ll show you how to replace one string with another string in Java. This is probably the easiest Java program to replace one string with another string. So let’s get started.

In my previous post, I have shown you How to replace String Characters In Java Using replace() Method?
So this time I thought this gonna be helpful to the Java Learners.

Java program to replace one string with another string

For example, You have a string like this:

Hey there, I am a string and I am going to be changed soon

Now you want to change the string like this:

Hey there, I am a string and I have changed

So how to do that?



I will show you two methods to do this. But choose the best one for you.

How to read a specific line from a text file in Java

public class ReplaceString {
    public static void main(String args[]) {
        String string1 = new String("Hey there, I am a string and I am going to be changed soon");
        System.out.println("Original String is ': " + string1);
        System.out.println("String after replacing : " + S1.replace("I am going to be changed soon", "I have changed"));
    }
}

This will give you your desired result.

Here what we have done is, simply used the replace() method. This method returns a string. Generally, it is used to replace all the old characters or characters sequence to new characters or character sequence.

FizzBuzz Problem In Java- A java code to solve FizzBuzz problem
But another easy way is:

public class ReplaceString {
    public static void main(String args[]) {
        String string1 = new String("Hey there, I am a string and I am going to be changed soon");
        String string2 = new String("Hey there, I am a string and I have changed");
        System.out.println("Original String is ': " + string1);
        string1=string2;
        System.out.println("String after replacing : " + S1);
    }
}

I know this method is quite funny. As we have done nothing at all. But our main objective was to replace one string with another and we did it.

 

Leave a Reply

Your email address will not be published. Required fields are marked *