Java String Shorten shorten(String s, int length, String suffix)

Here you can find the source of shorten(String s, int length, String suffix)

Description

shorten

License

Open Source License

Declaration

public static String shorten(String s, int length, String suffix) 

Method Source Code

//package com.java2s;
/*//from ww  w  . j  a  va 2s.  com
 * Copyright (C) 2009-2015 SM2 SOFTWARE & SERVICES MANAGEMENT
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program has been created in the hope that it will be useful.
 * It is distributed WITHOUT ANY WARRANTY of any Kind,
 * without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
 *
 * For more information, please contact SM2 Software & Services Management.
 * Mail: info@talaia-openppm.com
 * Web: http://www.talaia-openppm.com
 *
 * Module: utils
 * File: StringUtil.java
 * Create User: javier.hernandez
 * Create Date: 06/03/2015 14:35:37
 */

public class Main {
    public static String shorten(String s, int length) {
        return shorten(s, length, "...");
    }

    public static String shorten(String s, String suffix) {
        return shorten(s, 20, suffix);
    }

    public static String shorten(String s, int length, String suffix) {

        StringBuilder sb = null;

        if (s != null && suffix != null && s.length() > length) {
            for (int j = length; j >= 0; j--) {
                if (Character.isWhitespace(s.charAt(j))) {
                    length = j;

                    break;
                }
            }

            sb = new StringBuilder();

            sb.append(s.substring(0, length));
            sb.append(suffix);

        }

        return (sb == null ? null : sb.toString());
    }
}

Related

  1. shorten(String s)
  2. shorten(String s)
  3. shorten(String s)
  4. shorten(String s, int len)
  5. shorten(String s, int length)
  6. shorten(String s, int length, String suffix)
  7. shorten(String s, int max)
  8. shorten(String s, int maxLength)
  9. shorten(String script, int length)