- 1). Launch the program you use to edit Java programs.
- 2). Open one of your Java files and locate the "Main" method.
- 3). Paste the following code at the top of that method:
String originalString = "This is the original text string";
String subStringToRemove = "original text";
String replacementValue = "";
String blank = " ";
The variable "originalString" holds your original text string. The next variable, "subStringToRemove," contains the substring you want to find. The "replacementValue" variable has the replacement string, and "blank" defines a blank character. - 4). Add the following code below the code in Step 3:
String newString = originalString.replace(subStringToRemove + blank, replacementValue);
System.out.println(newString);
The first line executes Java's "replace" method. This method, a member of the "String" class, allows you to replace characters and words within a string. To get this method to remove a substring, the code assigns a null value to the "replacementValue" variable as shown in Step 3. The "blank" variable insures that no extra spaces appear in the resulting string. The variable "newString" holds that result. The last statement shows how the original string looks once Java removes the substring. - 5). Save the file and run it. The code will execute and remove "original text" from the original text string that contains "This is the original text string." The resulting string reads "This is the string."