Thibstars icon

Text - abbreviateWithImportantEnding

Thibstars | PRO | 02/17/17 08:35:37 AM UTC | 0 ⭐ | 306 👁️ | Never ⏰ | []
Java |

1.22 KB

|

None

|

0 👍

/

0 👎

public static String abbreviateWithImportantEnding(String s, int maxLength) {
        // Abbreviates with default split char
        return abbreviateWithImportantEnding(s, maxLength, "|");
    }
 
    public static String abbreviateWithImportantEnding(String s, int maxLength, String split) {
        String result;
        int minAbbrevLength = 3; // Max length must be greater than 3 to abbreviate the start string with StringUtils
 
        if (s.contains(split) && maxLength > minAbbrevLength) {
            String start = s.substring(0, s.lastIndexOf(split)); // First part of the String
            String end = s.substring(s.lastIndexOf(split), s.length()); // End part of the String (important)
 
            int endLength = end.length();
            int maxStart = maxLength - endLength;
            if (start.length() > minAbbrevLength && maxStart > minAbbrevLength) {
                start = StringUtils.abbreviate(start, maxStart);
            } else {
                String ellipsis = "...";
                start = start.isEmpty() ? "" : ellipsis; // Only add ellipsis when the start is not empty
                if (end.length() > minAbbrevLength) {
                    end = StringUtils.abbreviate(end, maxLength - ellipsis.length());
                }
            }
 
            result = start + end;
        } else {
            result = StringUtils.abbreviate(s, maxLength);
        }
 
        return result;
    }

Comments