Java Utililty Methods String Shorten

List of utility methods to do String Shorten

Description

The list of methods to do String Shorten are organized into topic(s).

Method

StringshortenString(String orig, int charsToRemove)
shorten String
if (charsToRemove <= 0) {
    return orig;
if (charsToRemove >= orig.length() - 1) {
    return orig.charAt(0) + "...";
int cut = orig.length() - charsToRemove;
int s1len = cut / 2 + cut % 2;
...
StringshortenString(String orig, int maxLength)
shorten String
if (orig == null || orig.length() <= maxLength) {
    return orig;
return orig.substring(0, maxLength);
StringshortenString(String s, int maxLength)
If the string s is longer than maxLength , the string is cut and "..."
if (s != null && s.length() > maxLength) {
    return s.substring(0, maxLength - 3) + "...";
} else {
    return s;
StringshortenString(String s, int requiredLength)
Shortens string to be no more than number of symbols specified
if (s != null && s.length() > requiredLength) {
    s = s.substring(0, requiredLength + 1);
    int space = s.lastIndexOf(" ");
    int lineFeed = s.lastIndexOf("\n");
    int tab = s.lastIndexOf("\t");
    if (space > 0 || lineFeed > 0 || tab > 0) {
        int cut = space > lineFeed ? (space > tab ? space : tab) : (lineFeed > tab ? lineFeed : tab);
        s = s.substring(0, cut);
...
StringshortenString(String source, int minLength, int maxLength, String suffix)
Shorten the string to the specifed lenght.
if (source == null || maxLength >= source.length()) {
    return source;
int i;
for (i = maxLength - 1; i >= 0; i--) {
    int type = Character.getType(source.charAt(i));
    if (type >= Character.DASH_PUNCTUATION && type <= Character.OTHER_PUNCTUATION) {
        break;
...
StringshortenString(String str, int i)
shorten String
if ((str != null) && (str.length() > i)) {
    str = str.substring(0, i) + "...";
return nullString(str);
StringshortenString(String string, int minimumLength, int lengthToShortenBy)
shorten String
int minIndex = Math.min(string.length(), minimumLength);
int maxIndex = string.length() - lengthToShortenBy;
return string.substring(0, Math.max(minIndex, maxIndex));
StringshortenString(String string, int targetLength, int maxDeviation)
shorten String
targetLength = Math.abs(targetLength);
maxDeviation = Math.abs(maxDeviation);
if (string == null || string.length() <= targetLength + maxDeviation) {
    return string;
int currentDeviation = 0;
while (currentDeviation <= maxDeviation) {
    try {
...
StringshortenStringForDisplay(String str, int desiredLen)
Shortens the given String to the desired length (for display to the user)
if (str.length() > desiredLen) {
    return str.substring(0, desiredLen - 3) + "...";
} else {
    return str;
StringshortenStringIfNecessary(String string, int maxLength, String suffixToAppend)
shorten String If Necessary
if (string == null)
    return null; 
return (string.length() > maxLength) ? string.substring(0, maxLength) + suffixToAppend : string;