How to remove a substring from a given String in Java

3 Answers

0 votes
public class MyClass {
    public static void main(String args[]) {
        String str = "Java C C++ Monty Python";
        String substr = "Monty" + " ";
         
        str= str.replace(substr, ""); 
         
        System.out.println(str);  
    }
}

    
    
/*
run:
    
Java C C++ Python
    
*/

 



answered Nov 12, 2023 by avibootz
edited Jun 4, 2024 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        String str = "Java C C++ Monty Python";
        String substr = "Monty" + " ";
         
        int startIndex = str.indexOf(substr);  
        int endIndex = startIndex + substr.length();  
         
        str = str.substring(0, startIndex) + str.substring(endIndex);  
         
        System.out.println(str);  
    }
}


    
/*
run:
    
Java C C++ Python
    
*/

 



answered Nov 12, 2023 by avibootz
edited Jun 4, 2024 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        String str = "Java C C++ Monty Python";
        String substr = "Monty" + " ";
         
        String[] parts = str.split("Monty ");
         
        str = parts[0] + parts[1]; 
         
        System.out.println(str);  
    }
}

    
    
/*
run:
    
Java C C++ Python
    
*/

 



answered Nov 12, 2023 by avibootz
edited Jun 4, 2024 by avibootz
...