Here you can find the source of truncate(String source, int maxLength, String cutoffReplacement)
Parameter | Description |
---|---|
source | the text to truncate |
maxLength | maximum length of the returned string including any cutoff relacements |
cutoffReplacement | a string that will be used to replace the cut off part (usually ...) or null |
public static String truncate(String source, int maxLength, String cutoffReplacement)
//package com.java2s; public class Main { /**/* ww w . j a v a 2s .co m*/ * Makes a best efford to truncate a string into the desired length. If the string * gets truncated an optional string can be used to replace the part that gets cut * off, the returned string (including replacement) will not be longer then maxLength. * It is best to use short replacement strings. If the replacement string is too long * or the maxLength too short to produce a non empty string (e.g. maxLength=3 and * replacement = "..." would result normally in "") then either the replacement or if * that is null (happens only if maxLength=0) the original string are returned * unchanged. * * @param source * the text to truncate * @param maxLength * maximum length of the returned string including any cutoff relacements * @param cutoffReplacement * a string that will be used to replace the cut off part (usually ...) or * null * @return A string with a maximum length of maxLength, unless * maxLength-cutoffReplacement.length()<=0 then the cutoffReplacement will * be returned unless that is null then the original string is returned. */ public static String truncate(String source, int maxLength, String cutoffReplacement) { if (source == null || source.length() <= maxLength) return source; int cutoffLength = maxLength; if (cutoffReplacement != null) cutoffLength -= cutoffReplacement.length(); if (cutoffLength <= 0) { if (cutoffReplacement != null) return cutoffReplacement; return source; } if (cutoffReplacement != null) return source.substring(0, cutoffLength) + cutoffReplacement; return source.substring(0, cutoffLength); } }