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:
- Using the
String.replace()
method:
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.
- Using the
String.substring()
method:
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.
- Using the
String.split()
method:
String s = "Hello World!";
String[] parts = s.split("World"); // {"Hello ", "!"}
String newString = parts[0] + parts[1]; // "Hello !"
This method splits the string into an array of substrings around the substring, and then concatenates the first and second elements of the array to create the new string.
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.