Here you can find the source of shortenString(String string, int targetLength, int maxDeviation)
public static String shortenString(String string, int targetLength, int maxDeviation)
//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) + " ..."; } }