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