Remove trailing substring from String in Java

Assuming you have a string initialized as String file = "[email protected]";.

if(file.endsWith("@2x.png"))
    file = file.substr(0, file.lastIndexOf("@2x.png"));

The endsWith(String) method returns a boolean determining if the string has a certain suffix. Depending on that you can replace the string with a substring of itself between the first character and before the index of the character that you are trying to remove.


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

Tags:

Java

String