Java - Write code to Abbreviate a string.

Requirements

Write code to Abbreviate a string.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String longName = "boo                                                             k2s.com";
        System.out.println(abbreviate(longName));
    }/* w  w w . j av a  2 s .c  o m*/

    /** Abbreviate a string.
     *  If the string is longer than 80 characters, truncate it by
     *  displaying the first 37 chars, then ". . .", then the last 38
     *  characters.
     *  If the <i>longName</i> argument is null, then the string
     *  "&gt;Unnamed&lt;" is returned.
     *  @param longName The string to be abbreviated.
     *  @return The possibly abbreviated name.
     *  @see #split(String)
     */
    public static String abbreviate(String longName) {
        // This method is used to abbreviate window titles so that long
        // file names may appear in the window title bar.  It is not
        // parameterized so that we can force a unified look and feel.
        // FIXME: it would be nice to split on a nearby space. 
        if (longName == null) {
            return "<Unnamed>";
        }

        if (longName.length() <= 80) {
            return longName;
        }

        return longName.substring(0, 37) + ". . ."
                + longName.substring(longName.length() - 38);
    }
}