class Main { public static void main(String[] args) { String str = "newBay", replace="new"; String replaceTo = "programmer"; System.out.println("Orignal string : " + str); System.out.println("New string : " + str.replace( replace, replaceTo)); } }
Output:
Orignal string : newBay New string : programmerBay
This is another way, but this time with lambda expression which was introduced in Java 8
@FunctionalInterface interface MyFunctionInterface { String replaceMe(String to,String with ); } class Main { public static void main(String[] args) { String str = "newBay", replace="new"; String replaceTo = "programmer"; MyFunctionInterface i = (r,rt) -> str.replace(r,rt); System.out.println("Original String : "+str); System.out.println("Original String : "+i.replaceMe(replace,replaceTo)); } }
Output:
Orignal string : newBay New string : programmerBay
Also read: Java program to replace a substring without using replace method
This post was last modified on July 4, 2022