Remove part of string in Java

JavaString

Java Problem Overview


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 Solutions


Solution 1 - Java

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));

Solution 2 - Java

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);

Solution 3 - Java

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)","");

Solution 4 - Java

originalString.replaceFirst("[(].*?[)]", "");

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

Solution 5 - Java

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, "");

Solution 6 - Java

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);

Solution 7 - Java

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];

Solution 8 - Java

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"

Solution 9 - Java

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

Solution 10 - Java

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)

Solution 11 - Java

// 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);
        
    }
}

Solution 12 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionzmkiView Question on Stackoverflow
Solution 1 - JavamprabhatView Answer on Stackoverflow
Solution 2 - JavaShawn JanasView Answer on Stackoverflow
Solution 3 - JavaMatt CashattView Answer on Stackoverflow
Solution 4 - Java1111161171159459134View Answer on Stackoverflow
Solution 5 - Javauser982733View Answer on Stackoverflow
Solution 6 - JavaGopal NairView Answer on Stackoverflow
Solution 7 - JavaNicolas EpaminondaView Answer on Stackoverflow
Solution 8 - JavaIgor VukovićView Answer on Stackoverflow
Solution 9 - JavaGiboltView Answer on Stackoverflow
Solution 10 - JavaGiboltView Answer on Stackoverflow
Solution 11 - JavaKIBOU HassanView Answer on Stackoverflow
Solution 12 - Javaslindsey3000View Answer on Stackoverflow