replace a substring – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Mon, 04 Jul 2022 06:37:26 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg replace a substring – Programmerbay https://programmerbay.com 32 32 Java Program to replace a substring in a String using replace() and Lambda Expression https://programmerbay.com/java-program-to-replace-a-substring-in-a-string-using-replace-and-lambda-expression/ https://programmerbay.com/java-program-to-replace-a-substring-in-a-string-using-replace-and-lambda-expression/#respond Thu, 27 Feb 2020 04:54:13 +0000 https://programmerbay.com/?p=6123 Program to replace a substring using replace method

Simple Program:

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

Program to replace a substring using Lambda Expression

@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

]]>
https://programmerbay.com/java-program-to-replace-a-substring-in-a-string-using-replace-and-lambda-expression/feed/ 0