Java Utililty Methods String Truncate

List of utility methods to do String Truncate

Description

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

Method

StringtruncateString(String s)
Chop long strings down to size for display purposes
if (s == null || s.length() < 28) {
    return s;
} else {
    return s.substring(27) + "...";
StringtruncateString(String s, int numChars)
truncate String
if (s != null && s.length() > numChars) {
    s = s.substring(0, numChars);
return s;
StringtruncateString(String source, int prefixLength, int totalLength)
Description: short a string to the format xx...xxxx
if (source.length() <= totalLength) {
    return source;
if (prefixLength + 3 > totalLength) {
    throw new IllegalArgumentException("total length meust be larger than prefix length + 3!");
int tokeep = totalLength - prefixLength - 3;
return source.substring(0, prefixLength) + "..."
...
StringtruncateString(String source, String suffix)
Returns a new string that is source with suffix removed from the end.
return (source.endsWith(suffix)) ? truncateString(source, suffix.length()) : source;
StringtruncateString(String str, int length)
truncate String
if (str == null)
    return null;
String retValue;
if (str.length() <= length) {
    retValue = str;
} else {
    retValue = str.substring(0, length);
return retValue;
StringtruncateString(String str, int length, String suffix)
Truncate a string by the given length, cutting words if necessary.
if (str != null && length >= 0) {
    suffix = (suffix == null ? "" : suffix);
    if (str.length() > (length - suffix.length())) {
        int size = length - suffix.length();
        while (size < 0) {
            size++;
        str = str.substring(0, size) + suffix;
...
StringtruncateString(String str, int maxlen)
truncate String
return truncateString(str, maxlen, false);
StringtruncateString(String str, int size)
truncate String
if (size <= 0 || size > str.length()) {
    return str;
return str.substring(0, size);
StringtruncateString(String str, int toLen)
Truncate a given string str to given length toLen.
String newStr = null;
if (null == str) {
    return str;
if (toLen <= 0) {
    return "";
if (str.length() > toLen) {
...
StringtruncateString(String string, int maxLength)
Truncates a string to have at maximum maxLength characters.
Where truncation is necessary an ellipsis is appended to the truncated string.
if ((string != null) && (string.length() > maxLength)) {
    return string.substring(0, maxLength - ELLIPSIS.length() + 1) + ELLIPSIS;
} else {
    return string;