How to Remove substring from String in Java?23 Oct 2024 | 9 min read In Java, removing a substring from a string involves manipulating the original string to exclude the specified substring. This process can be achieved by various means, typically involving string handling methods that identify the position of the substring and then create a new string without the unwanted part. The fundamental concept revolves around leveraging Java's robust String API to effectively locate and eliminate the substring while maintaining the integrity of the remaining parts of the original string. Java provides several methods for removing substrings from Strings. ScenarioHere are a few scenarios where you might need to remove a substring from a string in Java: Cleaning Up User InputScenario: A web application collects user input, but some users include unwanted phrases or characters (e.g., "Please delete this" or HTML tags like <script>). Example: Removing all instances of a certain phrase or set of characters to sanitize the input. Formatting DataScenario: A program processes data files that include unnecessary headers or footers in each entry (e.g., "Report Start" or "Report End"). Example: Removing these headers and footers to standardize the data format before further processing. Removing Sensitive InformationScenario: An application logs error messages that inadvertently contain sensitive information such as passwords or API keys. Example: Removing these sensitive substrings before saving or displaying the log entries. Simplifying URLsScenario: A web scraper collects URLs that include tracking parameters (e.g., "?utm_source=newsletter"). Example: Stripping these parameters to get the base URL for cleaner storage and analysis. Text NormalizationScenario: An application processes text documents that include repetitive boilerplate phrases (e.g., "Best regards," at the end of emails). Example: Removing these phrases to normalize the text for better readability or analysis. Customizing OutputScenario: A templating engine generates dynamic content, but certain placeholders or tags (for example, "{{username}}") need to be removed in the final output. Example: Stripping out these placeholders to render the final document cleanly. Each of these scenarios involves the need to identify and remove specific substrings from larger strings to achieve a desired outcome, ensuring that the remaining text is clean, accurate, and ready for its intended use. 1) Using replace() MethodThe replace() method of the String class is overloaded to provide two different implementations of the same method and provides a straightforward way to remove a substring from a string. By replacing the unwanted substring with an empty string, we effectively remove it from the original string. This method is both intuitive and convenient, making it a popular choice for simple string manipulations. It can handle all occurrences of the substring, ensuring that the specified part is completely removed wherever it appears in the string. In the first approach, a new character is added to a string to replace every previous character. This way returns the string with the new characters after all the old characters have been updated. Syntax: The procedure returns this string if the new character cannot be located in the string. File Name: RemoveSubString.java Output: JavatPoint is for teaching purpose 2) Using CharSequenceThe second technique substitutes the desired string of characters for the CharSequence, which is just a collection of characters. CharSequence is an interface that represents a sequence of characters. It is implemented by several classes including String, StringBuilder, and StringBuffer. To remove a specific substring from a string, you can utilize the replace method, which accepts two CharSequence arguments. By passing the substring we want to remove as the first argument and an empty string as the second argument, you can effectively remove the specified substring from the original string. This approach leverages the flexibility and power of CharSequence to handle various character sequences in a unified manner. Syntax: This operation and the first merely differ in that it substitutes a string of characters. File Name: RemoveSubstringExample.java Output: Hello, this is a string. 3) Replace the Substring with an Empty StringReplacing a substring with an empty string is a common technique used to remove that substring from the original string. By using the replace() method and specifying the substring we want to remove as the first argument and an empty string ("") as the second argument, we effectively eliminate the specified substring. This approach is straightforward and leverages the powerful string manipulation capabilities provided by the Java String class. The result is a new string with all instances of the specified substring removed, leaving the rest of the original string intact. Java allows us to easily replace a substring we want to delete from the String with an empty String. Syntax: File Name: RemoveSubStringFromString.java Output: ![]() 4) Using String's replaceFirst() MethodThe replaceFirst() method provided by the String class allows us to remove the first occurrence of a specific substring from a string. It takes two parameters: the substring we want to replace and the replacement string. By passing an empty string ("") as the replacement, we effectively remove the first occurrence of the specified substring from the original string. This approach is useful when we only want to remove the first occurrence of a substring while leaving any subsequent occurrences unchanged. The replaceFirst() method provides a convenient and efficient way to perform such string manipulations in Java. This method searches for a string that matches a regular expression and, if one is found, replaces it with the given string. Behind the scenes, this function extracts the text using a regular expression by using the compile() and matcher() methods of the Pattern class. Syntax: A regular expression will be created to extract a number from a string and replace it with another number as a string. Note: Only the first two digits of the string will be changed by this number; the remaining digits will remain unchanged.File Name: RemoveSubStringFromString.java Output: ![]() 5) Using replaceAll() MethodThe replaceAll() method, as contrast to replaceFirst(), utilizes a regular expression to replace every instance of the string. The replaceAll() method provided by the String class allows us to replace all occurrences of a specific substring or pattern within a string with another substring or pattern. It takes two parameters: the regular expression pattern representing the substring or pattern we want to replace, and the replacement string or pattern. When using replaceAll(), we define a regular expression pattern that matches the substrings or patterns you wish to replace. By passing this pattern as the first argument and the replacement string or pattern as the second argument, we effectively replace all occurrences of the specified substring or pattern with the replacement value. It is useful for performing global replacements within a string, such as removing all instances of a certain substring, replacing specific patterns, or transforming text based on a pattern match. It provides a flexible and powerful way to manipulate strings in Java, particularly when dealing with complex replacement scenarios involving patterns. Similar to replaceFirst(), this method extracts a string using a regular expression by using the compile() and matcher() methods. It also produces a PatternSyntaxException if the regular expression is incorrect. Syntax: File Name: RemoveSubStringFromString.java Output: ![]() 6) Using String Builder's delete() MethodThe StringBuilder class provides a mutable sequence of characters, allowing us to manipulate strings efficiently. The delete() method of StringBuilder enables us to remove a range of characters from the sequence. In order to add and remove characters from a string, the StringBuilder holds a modifiable sequence of characters. A string builder with an initial capacity of 16 characters is created by the empty StringBuilder function Object() { [native code] }, and if the internal buffer overflows, a larger string builder is created automatically. The delete() method takes two parameters: the starting index (inclusive) and the ending index (exclusive) of the characters to be removed. After calling delete(), the characters in the specified range are removed from the StringBuilder, and the remaining characters are shifted to fill the gap. The start and end of the substring to be deleted from the string are specified as the first and second int parameters of the delete() function. The last index is exclusive since it subtracts one from the second parameter, but the start index is inclusive. This method is useful when we need to remove a specific portion of a string stored in a StringBuilder, such as trimming unwanted characters, deleting a substring, or performing other types of character removal operations. It provides a convenient and efficient way to modify string data without creating new string objects that can be beneficial for performance-sensitive tasks. Syntax: We will employ a regular expression that pulls out all numbers from a string and substitutes numbers for every instance. \d: This regular expression recognizes any digit between 0 and 9. File Name: RemoveSubStringExample.java Output: ![]() 7) Using StringBuilder replace() MethodThe sole difference between the replace() function and the delete() method is the third parameter that is used to replace the characters that have been removed from the string. The StringBuilder class offers mutable strings, allowing for efficient manipulation of character sequences. The replace() method enables you to replace a specific range of characters in a StringBuilder with another string. The replace() method takes three parameters: the starting index (inclusive) of the substring to be replaced, the ending index (exclusive) of the substring to be replaced, and the replacement string. After calling replace(), the characters in the specified range are replaced by the characters of the replacement string. If a large string needs to be replaced, the size will be increased to accommodate the length of the string. This method is useful when we need to modify portions of a string stored in a StringBuilder, such as replacing substrings, updating specific segments, or performing other types of character replacement operations. It provides a flexible and efficient way to modify string data in place without creating new string objects, which can be advantageous for performance-critical applications. Syntax: The function toString() { [native code] }() function can be used to print the updated string after this method returns a StringBuilder. File Name: RemoveSubStringFromString.java Output: ![]() ConclusionWe have learnt how to replace and delete characters to remove a substring from a string in this section. The techniques presented include the use of the StringBuilder delete() and replace() methods, as well as the string replace(), replaceFirst(), and replaceAll() functions. |
The concept of inheritance represents an essential principle among the four fundamental aspects of Object-Oriented Programming (OOP) in Java . A subclass can receive all fields and methods from its superclass through the inheritance mechanism. The feature enables developers to reuse code blocks and create maintainable and expandable...
3 min read
Java 9 introduced several new features and enhancements to further improve the language's capabilities. Among these additions are the orTimeout() and completeOnTimeout() methods that are designed to enhance the handling of timeouts in CompletableFuture instances. These methods provide developers with more control and flexibility when dealing...
4 min read
The Java java.util package contains the AbstractSequentialList class, which offers a fundamental implementation of the List interface in order to reduce the tasks involved in implementing this interface using a "sequential access" data storage (such a linked list). To get rid of every element from a...
3 min read
In this section, we will learn what is Carmichael number and also create Java programs to check if the given number is a Carmichael number or not. The Carmichael numbers program is frequently asked in Java coding interviews and academics. Carmichael Numbers A composite number n that are...
4 min read
The Tribonacci series is similar to the Fibonacci series. The Tribonacci sequence is a generalization of the Fibonacci sequence where each term is the sum of the three preceding terms. Tribonacci Series A Tribonacci sequence or series is a sequence of integers such that each term from the...
2 min read
A built-in Java method that allows you to set a value at any location in the AtomicLongArray is called Java.util.concurrent.atomic.AtomicLongArray.set(). This function modifies the value at that index by accepting as an argument the AtomicLongArray's index value. There is absolutely nothing that this method returns....
3 min read
The sorting is a way to arrange elements of a list or array in a certain order. The order may be in ascending or descending order. The numerical and lexicographical (alphabetical) order is a widely used order. In this section, we will learn how to sort array...
6 min read
Java, one of the most popular programming languages in the world, offers a rich set of features that allow developers to write powerful and efficient code. One such feature is the ability to create compound statements. Compound statements, also known as block statements, play a...
5 min read
The enable web based interactions online with HTTP or HTTPS within various software systems. Services allow various software to interoperate no matter the language that is used, the operating system and even the architecture that was used and so on. These two are the common web...
4 min read
The Stream.skip(long n) method in Java is an important part of the Stream API which was introduced in Java 8. It enables developers to build pipelines of operations on data sets. The skip() method is especially useful for skipping a certain number of elements in...
9 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India