How to replace a String with another String in Java
Posted On
Posted By admin
In this blog post, I will be demonstrating how you can replace a String with another String via Java. Consider the following code snippet:
package learnjava.strings; public class ReplaceStringDemo { public static void main(String[] args) { String str = "Good Morning. Another String with the word Morning."; String newStr= str.replace("Morning", "Night"); System.out.println("Original String="+str); System.out.println("new String="+newStr); } }
There is a String.replace method. It accepts as input the String to be replaced and the value with which it should be replaced. It then replaces each occurrence of the first String with the second String. This method actually accepts CharSequence as input. CharSequence is an interface. The String class implements this interface and so you can pass in a String value to this method.
So when you run the code above, it will print the following output to the console:
Original String=Good Morning. Another String with the word Morning. new String=Good Night. Another String with the word Night.
If you like this post, please do let me know via the comments box below. You can also connect with me via my Facebook Page or subscribe to my Youtube channel!