GhostCat
GhostCat

Reputation: 140475

Algorithms for "shortening" strings?

I am looking for elegant ways to "shorten" the (user provided) names of object. More precisely:

Now I am looking for thoughts on how to generate these "reduced" names, based on the 64-char name.

With "elegant" I am wondering about any useful ideas that "might" allow the user to recognize something with value within the shortened string. Like, if the name is "Production Test Item A5"; then maybe "PTIA5" might (or might not) tell the user something useful.

Upvotes: 1

Views: 3705

Answers (2)

Steve Farmwald
Steve Farmwald

Reputation: 41

I needed to shorten names to function as column names in a database. Ideally, the names should be recognizable for users. I set up a dictionary of patterns for commonly occuring words with corresponding "abbreviations". This was applied ONLY to those names which were over the limit of 30 characters.

Upvotes: 2

user1438038
user1438038

Reputation: 6069

Apply a substring method to the long version, trim it, in case there are any whitespace characters at the end, optionally remove any special characters from the very end (such as dashes) and finally add a dot, in case you want to indicate your abbreviation that way.

Just a quick hack to get you started:

  String longVersion = "Aswaghtde-5d";

  // Get substring 0..8 characters
  String shortVersion = longVersion.substring(0, (longVersion.length() < 8 ? longVersion.length() : 8));

  // Remove whitespace characters from end of String
  shortVersion = shortVersion.trim();

  // Remove any non-characters from end of String
  shortVersion = shortVersion.replaceAll("[^a-zA-Z0-9\\s]+$", "");

  // Add dot to end
  shortVersion = shortVersion.substring(0, (shortVersion.length() < 8 ? shortVersion.length() : shortVersion.length() - 1)) + ".";

  System.out.println(shortVersion);

Upvotes: 2

Related Questions