Sunday, January 22, 2012

Delete a Substring From a String Using Java

Task:- Delete a substring from a String.
Solution: There are two approaches for the same. We might need to delete a specific substring from the String, or we might need to delete a substring using the index positions. Both the approaches are shown below:-

Delete a specific substring from a string. The below code deletes the word "substring" from the original String.
The code is given below:-

 package javaTest1;

 //Delete using the name of the substring to be deleted
 public class DeleteSubString1 {
    public static void main(String[] args) {
        String oldStr = "Hello, this is the string from which a substring will be deleted";
        String delStr = "substring";
        String newStr;

        newStr = oldStr.replace(delStr, "");

        System.out.println(oldStr);
        System.out.println(newStr);
    }
 }

When the above code is executed the output is:-
 Hello, this is the string from which a substring will be deleted
 Hello, this is the string from which a  will be deleted

Delete a substring from a string using index positions. The below code deletes the word "substring" from the original String based on the index positions provided.
The code is given below:-
 package javaTest1;

 //Delete using the index positions to be deleted
 public class DeleteSubString2 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String oldStr = "Hello, this is the string from which a substring will be deleted";
        String delStr;
        String newStr;

        delStr = oldStr.substring(39, 48);
        newStr = oldStr.replace(delStr, "");

        System.out.println(oldStr);
        System.out.println(newStr);
    }
 }

When the above code is run, the output is:-
 Hello, this is the string from which a substring will be deleted
 Hello, this is the string from which a  will be deleted


Related Articles
Substring Index Out of Range Exception
Search and Replace a Substring in Java Example