9

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?

3
  • 2
    Check out the substring and endsWith methods from the String class Commented Feb 7, 2015 at 21:56
  • It's well documented: String#endsWith Commented Feb 7, 2015 at 21:57
  • Do you want to replace always @2x.png or any substring which starts with @ till end? Commented Feb 7, 2015 at 22:03

8 Answers 8

12

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

String.lastIndexOf can find the substring anywhere in the string, not just at the end. You should check str.endsWith(suffix) instead, and you can then inline the call to lastIndexOf.
12
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);

2 Comments

IMHO, this should be the accepted answer. It is the most efficient solution : the suffix is matched only once, contrary to the other solutions based on endsWith()+lastIndexOf().
Moreover, the currently accepted solution may delete way more than the suffix...
9

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

if(file.endsWith("@2x.png"))
    file = file.substring(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 starting with the first character and ending before the index of the character that you are trying to remove.

2 Comments

The index cannot be -1 as the string is already checked to end with "@2x.png"
lastIndexOf is more correct since we need to remove the specified string only at the end. indexOf returns the first occurence of the specified string but in this case, we need the last occurence of that specified string. .endsWith("@2x.png") gives us the assurance that the lastIndexOf is actually @2x.png. @Pshemo
1
public static void main(String [] args){

    String word = "[email protected]";

    word = word.replace("@2x.png", "");

    System.out.println(word);
}

3 Comments

This does not remove that string from the end. The string for example could be "@[email protected]" and that should result to "@2x.png" not "" as this would tamper with the objective of the asker.
I'm not sure I know what you mean. I just ran the code again and the output was...... "am.sunrise.ios" I'm not very experienced at this so if I'm missing something then please help me understand.
Your solution removes "@2x.png" from the string. However it does not check if it is at the end of the string, as it will be removed regardless of being at the beginning of the string
1

If you want to generally remove entire content of string from @ till end you can use

yourString = yourString.replaceAll("@.*","");

where @.* is regex (regular expression) representing substring starting with @ and having any character after it (represented by .) zero or more times (represented by *).

In case there will be no @xxx part your string will be unchanged.


If you want to change only this particular substring @2x.png (and not substirng like @3x.png) while making sure that it is placed at end of your string you can use

yourString = yourString.replaceAll("@2x\\.png$","");

where

  • $ represents end of string
  • \\. represents . literal (we need to escape it since like shown earlier . is metacharacter representing any character)

Comments

1

Since I was trying to do this on an ArrayList of items similarly styled I ended up using the following code:

    for (int image = 0; image < IBImages.size(); image++) {
        IBImages.set(image, IBImages.get(image).split("~")[0].split("@")[0].split(".png")[0]);
    }

If I have a list of images with the names

[am.sunrise.ios.png, [email protected], [email protected], am.sunrise.ios~ipad.png, [email protected]]

This allows me to split the string into 2 parts. For example, "am.sunrise.ios~ipad.png" will be split into "am.sunrise.ios" and "~ipad.png" if I split on "~". I can just get the first part back by referencing [0]. Therefore I get what I'm looking for in one line of code.

Note that image is "am.sunrise.ios~ipad.png"

Comments

0

You could use String.split():

public static void main(String [] args){
  String word = "[email protected]";
  String[] parts = word.split("@");
  if (parts.length == 2) {
    System.out.println("looks like user@host...");
    System.out.println("User: " + parts[0]);
    System.out.println("Host: " + parts[1]);
  }
}

Then you haven an array of Strings, where the first element contains the part before "@" and the second element the part after the "@".

Comments

-1

Combining the answers 1 and 2:

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

if (str.endsWith(search)) {
  str = str.substring(0, str.lastIndexOf(search));
}

1 Comment

This wastes performance for searching the string twice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.