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?
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.
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.
With the replaceAll() method, you can use an empty String to remove a substring from a string. Syntax: string. replace(No.
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);
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);
}
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