Advertisement
Thibstars

Text - abbreviateWithImportantEnding

Feb 17th, 2017
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.22 KB | None | 0 0
  1. public static String abbreviateWithImportantEnding(String s, int maxLength) {
  2.         // Abbreviates with default split char
  3.         return abbreviateWithImportantEnding(s, maxLength, "|");
  4.     }
  5.  
  6.     public static String abbreviateWithImportantEnding(String s, int maxLength, String split) {
  7.         String result;
  8.         int minAbbrevLength = 3; // Max length must be greater than 3 to abbreviate the start string with StringUtils
  9.  
  10.         if (s.contains(split) && maxLength > minAbbrevLength) {
  11.             String start = s.substring(0, s.lastIndexOf(split)); // First part of the String
  12.             String end = s.substring(s.lastIndexOf(split), s.length()); // End part of the String (important)
  13.  
  14.             int endLength = end.length();
  15.             int maxStart = maxLength - endLength;
  16.             if (start.length() > minAbbrevLength && maxStart > minAbbrevLength) {
  17.                 start = StringUtils.abbreviate(start, maxStart);
  18.             } else {
  19.                 String ellipsis = "...";
  20.                 start = start.isEmpty() ? "" : ellipsis; // Only add ellipsis when the start is not empty
  21.                 if (end.length() > minAbbrevLength) {
  22.                     end = StringUtils.abbreviate(end, maxLength - ellipsis.length());
  23.                 }
  24.             }
  25.  
  26.             result = start + end;
  27.         } else {
  28.             result = StringUtils.abbreviate(s, maxLength);
  29.         }
  30.  
  31.         return result;
  32.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement