92

I want to remove a part of string from one character, that is:

Source string:

manchester united (with nice players)

Target string:

manchester united
Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
zmki
  • 1,173
  • 2
  • 8
  • 8
  • 5
    How do you know which part to keep and which part to discard? Without knowing that, it is impossible to answer your question? – Raedwald Jul 09 '13 at 18:26

12 Answers12

175

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));
Community
  • 1
  • 1
mprabhat
  • 20,107
  • 7
  • 46
  • 63
36

String Replace

String s = "manchester united (with nice players)";
s = s.replace(" (with nice players)", "");

Edit:

By Index

s = s.substring(0, s.indexOf("(") - 1);
Gerrit Griebel
  • 405
  • 3
  • 10
Shawn Janas
  • 2,693
  • 2
  • 14
  • 10
23

Use String.Replace():

http://www.daniweb.com/software-development/java/threads/73139

Example:

String original = "manchester united (with nice players)";
String newString = original.replace(" (with nice players)","");
Da2da2
  • 57
  • 2
  • 3
  • 13
Matt Cashatt
  • 23,490
  • 28
  • 78
  • 111
  • I wasn't the downvoter but perhaps because you put Replace in the wrong case? – Mike Kwan Jan 01 '12 at 20:00
  • 1
    Upvoted to negate the effect of a drive-by (i.e., unexplained and apparently specious) down vote. – Gayot Fow Jan 02 '12 at 00:35
  • It's not necessary that the string will be same as the example given. So you cannot use replace. – Confuse Apr 12 '15 at 08:52
  • There is performance comparison here , String replace method uses regular expression under the hood. https://stackoverflow.com/questions/16228992/commons-lang-stringutils-replace-performance-vs-string-replace – Igor Vuković Apr 11 '18 at 12:50
12
originalString.replaceFirst("[(].*?[)]", "");

https://ideone.com/jsZhSC
replaceFirst() can be replaced by replaceAll()

1111161171159459134
  • 1,216
  • 2
  • 18
  • 28
8

Using StringBuilder, you can replace the following way.

StringBuilder str = new StringBuilder("manchester united (with nice players)");
int startIdx = str.indexOf("(");
int endIdx = str.indexOf(")");
str.replace(++startIdx, endIdx, "");
6

You should use the substring() method of String object.

Here is an example code:

Assumption: I am assuming here that you want to retrieve the string till the first parenthesis

String strTest = "manchester united(with nice players)";
/*Get the substring from the original string, with starting index 0, and ending index as position of th first parenthesis - 1 */
String strSub = strTest.subString(0,strTest.getIndex("(")-1);
Gopal Nair
  • 830
  • 4
  • 7
6

I would at first split the original string into an array of String with a token " (" and the String at position 0 of the output array is what you would like to have.

String[] output = originalString.split(" (");

String result = output[0];
Nicolas Epaminonda
  • 181
  • 1
  • 3
  • 13
2

Using StringUtils from commons lang

A null source string will return null. An empty ("") source string will return the empty string. A null remove string will return the source string. An empty ("") remove string will return the source string.

String str = StringUtils.remove("Test remove", "remove");
System.out.println(str);
//result will be "Test"
Igor Vuković
  • 742
  • 12
  • 25
2

If you just need to remove everything after the "(", try this. Does nothing if no parentheses.

StringUtils.substringBefore(str, "(");

If there may be content after the end parentheses, try this.

String toRemove = StringUtils.substringBetween(str, "(", ")");
String result = StringUtils.remove(str, "(" + toRemove + ")"); 

To remove end spaces, use str.trim()

Apache StringUtils functions are null-, empty-, and no match- safe

Gibolt
  • 42,564
  • 15
  • 187
  • 127
2

Kotlin Solution

If you are removing a specific string from the end, use removeSuffix (Documentation)

var text = "one(two"
text = text.removeSuffix("(two") // "one"

If the suffix does not exist in the string, it just returns the original

var text = "one(three"
text = text.removeSuffix("(two") // "one(three"

If you want to remove after a character, use

// Each results in "one"

text = text.replaceAfter("(", "").dropLast(1) // You should check char is present before `dropLast`
// or
text = text.removeRange(text.indexOf("("), text.length)
// or
text = text.replaceRange(text.indexOf("("), text.length, "")

You can also check out removePrefix, removeRange, removeSurrounding, and replaceAfterLast which are similar

The Full List is here: (Documentation)

Gibolt
  • 42,564
  • 15
  • 187
  • 127
1
// Java program to remove a substring from a string
public class RemoveSubString {

    public static void main(String[] args) {
        String master = "1,2,3,4,5";
        String to_remove="3,";

        String new_string = master.replace(to_remove, "");
        // the above line replaces the t_remove string with blank string in master

        System.out.println(master);
        System.out.println(new_string);

    }
}
KIBOU Hassan
  • 381
  • 4
  • 13
0

You could use replace to fix your string. The following will return everything before a "(" and also strip all leading and trailing whitespace. If the string starts with a "(" it will just leave it as is.

str = "manchester united (with nice players)"
matched = str.match(/.*(?=\()/)
str.replace(matched[0].strip) if matched
slindsey3000
  • 4,053
  • 5
  • 36
  • 56