Removing a String from a String in Java

One of the common text processing requirements is to remove a specific substring from a given string. For example, let us assume we have string "1,2,3,4,5" and we want to remove "3," from it to get the new string "1,2,4,5". The following Java program demonstrates how this can be achieved.

Java Program to Remove a Substring from a String

// Java program to remove a substring from a string
public class RemoveSubString {
    public static void main(String[] args) {
        String master = "1,2,3,4,5";
        String to_remove="3,";
        String new_string = master.replace(to_remove, "");
        // the above line replaces the t_remove string with blank string in master

The key method here is replace(). This can be called on a string to replace the first parameter with the second parameter. When the second parameter is a blank string, it effectively deletes the substring from the main string.