How To Remove A Substring From A String Java

Chapter: String Handling Last Updated: 22-08-2023 17:04:36 UTC

Program:

            /* ............... START ............... */
                
// Using replace() method:

String originalString = "Hello, this is a substring example.";
String substringToRemove = "substring ";

String modifiedString = originalString.replace(substringToRemove, "");
System.out.println(modifiedString);

// Using replaceAll() method with Regular Expression:

String originalString = "Hello, this is a substring example.";
String substringToRemove = "substring ";

String modifiedString = originalString.replaceAll(substringToRemove, "");
System.out.println(modifiedString);


// Using substring() method:

String originalString = "Hello, this is a substring example.";
int startIndex = 18; // Starting index of the substring
int endIndex = 28;   // Ending index of the substring

String modifiedString = originalString.substring(0, startIndex) + originalString.substring(endIndex);
System.out.println(modifiedString);



                /* ............... END ............... */
        

Notes:

  • Using replace() method: The replace() method allows you to replace occurrences of a specified substring with another substring. To remove a substring, you can replace it with an empty string.
  • Using replaceAll() method with Regular Expression: The replaceAll() method also accepts a regular expression pattern. You can use this to match and replace substrings.
  • Using substring() method: If the substring you want to remove is at a specific index range, you can use the substring() method to create a new string excluding the substring you want to remove.
  • Remember that these methods will create a new string with the modified content. Strings in Java are immutable, meaning they cannot be changed once created. So, these methods will create a new string with the desired modification rather than modifying the original string in place.

Tags

How to remove a substring from a string java #Java substring

Similar Programs Chapter Last Updated
How To Check If A String Contains A Particular Substring In Java String Handling 22-08-2023
How To Split A String Into Substrings in Java String Handling 22-08-2023
Java Program To Remove Repeated Characters In A String String Handling 15-08-2023
Java Code To Check If String Contains Specific Characters String Handling 03-06-2023
How To Count The Number Of Cccurrences Of Each Character In A String In Java String Handling 03-06-2023
Java Program To Replace A Character In A String String Handling 03-06-2023
Java Program To Split A String String Handling 03-06-2023
String Length Implementation Java String Handling 02-12-2019

1