Java String Shorten shortenString(String string, int targetLength, int maxDeviation)

Here you can find the source of shortenString(String string, int targetLength, int maxDeviation)

Description

shorten String

License

BSD License

Declaration

public static String shortenString(String string, int targetLength,
            int maxDeviation) 

Method Source Code

//package com.java2s;
/**//from ww  w . j  a  v  a 2  s  . c  o m
 * The contents of this file are subject to the license and copyright
 * detailed in the LICENSE and NOTICE files at the root of the source
 * tree and available online at
 *
 * http://www.dspace.org/license/
 */

public class Main {
    public static String shortenString(String string, int targetLength,
            int maxDeviation) {
        targetLength = Math.abs(targetLength);
        maxDeviation = Math.abs(maxDeviation);
        if (string == null
                || string.length() <= targetLength + maxDeviation) {
            return string;
        }

        int currentDeviation = 0;
        while (currentDeviation <= maxDeviation) {
            try {
                if (string.charAt(targetLength) == ' ') {
                    return string.substring(0, targetLength) + " ...";
                }
                if (string.charAt(targetLength + currentDeviation) == ' ') {
                    return string.substring(0, targetLength
                            + currentDeviation)
                            + " ...";
                }
                if (string.charAt(targetLength - currentDeviation) == ' ') {
                    return string.substring(0, targetLength
                            - currentDeviation)
                            + " ...";
                }
            } catch (Exception e) {
                //just in case
            }

            currentDeviation++;
        }

        return string.substring(0, targetLength) + " ...";

    }
}

Related

  1. shortenString(String s, int maxLength)
  2. shortenString(String s, int requiredLength)
  3. shortenString(String source, int minLength, int maxLength, String suffix)
  4. shortenString(String str, int i)
  5. shortenString(String string, int minimumLength, int lengthToShortenBy)
  6. shortenStringForDisplay(String str, int desiredLen)
  7. shortenStringIfNecessary(String string, int maxLength, String suffixToAppend)
  8. shortenStringsByRemovingVowelsToFit(String s1, String s2, int maximumStringLength)
  9. shortenTagString(String longTag)