I want to remove a part of string from one character, that is:
Source string:
manchester united (with nice players)
Target string:
manchester united
Java Remove substring from String Notice that replaceAll and replaceFirst methods first argument is a regular expression, we can use it to remove a pattern from string. Below code snippet will remove all small case letters from the string.
You can also remove a specified character or substring from a string by calling the String. Replace(String, String) method and specifying an empty string (String. Empty) as the replacement. The following example removes all commas from a string.
There are multiple ways to do it. If you have the string which you want to replace you can use the replace
or replaceAll
methods of the String
class. If you are looking to replace a substring you can get the substring using the substring
API.
For example
String str = "manchester united (with nice players)"; System.out.println(str.replace("(with nice players)", "")); int index = str.indexOf("("); System.out.println(str.substring(0, index));
To replace content within "()" you can use:
int startIndex = str.indexOf("("); int endIndex = str.indexOf(")"); String replacement = "I AM JUST A REPLACEMENT"; String toBeReplaced = str.substring(startIndex + 1, endIndex); System.out.println(str.replace(toBeReplaced, replacement));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With