by BehindJava

How to remove substring from String in Java

Home » java » How to remove substring from String in Java

In this post, we will see how to remove substring from String in java.

There are multiple ways to remove substring from String in java.

Using String’s replace method to remove substring from String in Java

This method belongs to the Java String class and is overloaded to provide two different implementations of the same method.

The first method introduces a new character to a string that is used to replace all the old characters in that string.

After all the old characters are replaced, the method returns the string with the new characters.

If the new character is not found in the string, the method returns this string.

public class RemoveSubStringString
{
    public static void main(String[] args) {
 
        String description = "mesquite in your cellar";
        String replace = description.replace('e', 'o');
        System.out.println(replace);
    }
}

Output:

mosquito in your collar

The second method replaces a CharSequence which is simply a sequence of characters with the desired sequence of characters from a string.

This method works the same way as the first method, only that it replaces a sequence of characters.

public class RemoveSubStringString
{
    public static void main(String[] arg){
        String fruit = "Mary likes apples";
        String replace = fruit.replace("apples", "mangoes");
        System.out.println(replace);
    }
}

Output:

Mary likes mangoes

If you want to remove substring from the String in java, you can simply replace the substring with empty String.

Here is an example:

public class RemoveSubStringFromStringMain {
    public static void main(String[] arg) {
        String fruit = "Mary likes apples";
        String replace = fruit.replace("apples", "");
        System.out.println(replace);
    }
}

Output:

Mary likes

Using String’s replaceFirst method to remove substring from String in Java This method uses a regular expression to identify a string that matches the regular expression and is replaced with the passed string if present.

This method uses compile() and matcher() methods from the Pattern class behind the scenes to extract the string using the regular expression.

The method returns a string, and if the regular expression is invalid, the method throws a PatternSyntaxException error.

We will create a regular expression that extracts a number from a string and replaces it with another number as a string.

Note that this number will only replace the first two numbers in the string, and the other numbers will not be altered.

public class RemoveSubStringFromStringMain {
    public static void main(String[] arg) {
        String age = "Peter is 29 years old, and Jane is 60 years old";
        String replaceFirst = age.replaceFirst("\\d\\d", "30");
        System.out.println(replaceFirst);
    }
}

Output:

Peter is 30 years old and Jane is 60 years old

If you want to remove substring from String, you can use empty String with replaceFirst() method

Here is an example:

public class RemoveSubStringFromStringMain {
    public static void main(String[] arg) {
        String age = "Peter is 29 years old, and Jane is 60 years old";
        String replaceFirst = age.replaceFirst("\\d\\d", "");
        System.out.println(replaceFirst);
    }
}

Output:

Peter is years old, and Jane is 60 years old

Using String’s replaceAll method to remove substring from String in Java

Unlike thereplaceFirst, thereplaceAll method uses the regular expression to replace all the occurrences in the string.

Similar toreplaceFirst, This method uses compile() and matcher() methods to extract a string using a regular expression and also throws a PatternSyntaxException when the regular expression is invalid.

We will use a regular expression that extracts all numbers from a string and replaces all the occurrences with a number.

\d – This is a regular expression that matches any digit from 0 to 9.

public class RemoveSubStringFromStringMain {
    public static void main(String[] arg) {
        String replaceAll = "Peter is 29 years old, and Jane is 60 years old";
        String replaceAllNumbers = replaceAll.replaceAll("\\d\\d", "30");
        System.out.println(replaceAllNumbers);
    }
}

Output:

Peter is 30 years old and Jane is 30 years old

If you want to remove substring from String, you can use empty String with replaceAll() method

Here is an example:

public class RemoveSubStringFromStringMain {
    public static void main(String[] arg) {
        String replaceAll = "Peter is 29 years old, and Jane is 60 years old";
        String replaceAllNumbers = replaceAll.replaceAll("\\d\\d", "");
        System.out.println(replaceAllNumbers);
    }
}

Output:

Peter is years old, and Jane is years old

Using StringBuilder’s delete() method to remove substring from String in Java The StringBuilder contains a mutable sequence of characters used to modify a string by adding and removing characters.

The empty constructor of StringBuilder creates a string builder with an initial capacity of 16 characters, and if the internal buffer overflows, it is automatically made larger.

The delete() method accepts two int parameters indicating the start and the end of the substring to be removed from the string.

The start index is inclusive, while the last index is exclusive as it deducts 1 from the second parameter.

When the start is equal to the end, no changes are made, and a StringIndexOutOfBoundsException is thrown when the start is negative, greater than the length of the string, or greater than the end of the string.

public static void main(String[] args){
         StringBuilder stringBuilder = 
                new StringBuilder("Abdul quit drinking alcohol");
 
        //The last index = 19-1 = 18
        StringBuilder builder = stringBuilder.delete(11, 19);
 
        System.out.println(builder.toString());
}

Output:

Abdul quit alcohol

Using StringBuilder’s replace() method to remove substring from String in Java The replace() method is similar to the delete() method, only that it has a third parameter that replaces the characters that have been removed from the string.

If the string you want to replace is large, the size will be increased to accommodate its length.

This method also returns a StringBuilder, and you can use the toString() method to print out the modified string.

public static void main(String[] args){
         StringBuilder stringBuilder = 
                new StringBuilder("The car broke down on a hill");
 
        //The last index = 7-1 = 6
        StringBuilder builder = stringBuilder.replace(4, 7, "bike");
 
        System.out.println(builder.toString());
}

Output:

The bike broke down on a hill

Conclusion

In this tutorial, you have learned how to remove a substring from a string by replacing and deleting characters. The methods covered include using string replace(),replaceFirst(), replaceAll() and finally using StringBuilder delete() and replace() methods.