Java idiom for removing suffixes

by

Just because I keep finding myself writing this snippet of code to convince myself that have it correct (error checking not included…):

String full = "/some/where.mail";
String suffix = ".mail";

String prefix = full.substring(0, full.indexOf(suffix));

assert prefix.equals("/some/where");
Advertisements

2 Responses to “Java idiom for removing suffixes”

  1. Matthijs Kooijman Says:

    I don’t think that snippet is correct: When String full = “/some.mail/where.mail”; it will strip too much?

  2. Roland Turner Says:

    That is certainly true. There are also other issues around (at least) the full string being null, the suffix being null, or the suffix not appearing in the full string.

    The point of the snippet was more about avoiding an off-by-on-error (do I take the index and add one, subtract one, or use it as-is?) than about a comprehensive solution.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: