Skip to content

How can I remove a substring from a given String?

There are several ways to remove a substring from a given string in Java. Here are a few options:

  1. Using the String.replace() method:

java
String s = "Hello World!";
String newString = s.replace("World", "");  // "Hello !"

This method replaces all occurrences of the substring with an empty string. If you only want to replace the first occurrence, you can use the String.replaceFirst() method instead:

java
String s = "Hello World! World!";
String newString = s.replaceFirst("World", "");  // "Hello ! World!"
  1. Using the String.substring() method:

java
String s = "Hello World!";
int startIndex = s.indexOf("World");  // 6
int endIndex = startIndex + "World".length();  // 11
String newString = s.substring(0, startIndex) + s.substring(endIndex);  // "Hello !"

This method extracts the part of the string before the substring and the part after the substring, and concatenates them to create the new string. Note: indexOf() returns -1 if the substring is not found. Check for this condition to avoid StringIndexOutOfBoundsException.

  1. Using the String.split() method:

java
String s = "Hello World!";
String[] parts = s.split("World");  // {"Hello ", "!"}
String newString = String.join("", parts);  // "Hello !"

This method splits the string into an array of substrings around the target, and then concatenates all elements to create the new string. Note: split() treats the argument as a regular expression. Use Pattern.quote() to safely escape special characters.

These are just a few examples of how you can remove a substring from a given string in Java. There are many other ways to do this, and the best approach will depend on your specific requirements.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.