Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove trailing substring from String in Java

Tags:

java

string

I am looking to remove parts of a string if it ends in a certain string.

An example would be to take this string: "[email protected]"

And remove the @2x.png so it looks like: "am.sunrise.ios"

How would I go about checking to see if the end of a string contains "@2x.png" and remove it?

like image 482
tbcrawford Avatar asked Feb 07 '15 21:02

tbcrawford


People also ask

How do I remove a trailing character from a string in Java?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

How do I remove a substring from a string in Java?

In order to remove a substring from a Java StringBuilder Object, we use the delete() method. The delete() method removes characters in a range from the sequence. The delete() method has two parameters, start, and end. Characters are removed from start to end-1 index.

How do I remove a substring from a string?

With the replaceAll() method, you can use an empty String to remove a substring from a string. Syntax: string. replace(No.


2 Answers

private static String removeSuffixIfExists(String key, String suffix) {
    return key.endswith(suffix)
        ? key.substring(0, key.length() - suffix.length())
        : key; 
    }
}

String suffix = "@2x.png";
String key = "[email protected]";

String output = removeSuffixIfExists(key, suffix);

like image 130
Hannu Varjoranta Avatar answered Oct 07 '22 07:10

Hannu Varjoranta


You could check the lastIndexOf, and if it exists in the string, use substring to remove it:

String str = "[email protected]";
String search = "@2x.png";

int index = str.lastIndexOf(search);
if (index > 0) {
    str = str.substring(0, index);
}
like image 23
Mureinik Avatar answered Oct 07 '22 06:10

Mureinik