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

Stringtruncate(String str, int max)
Ensure that the given string is no more than 'max' characters long.
return (str.length() > max) ? str.substring(0, max) : str;
Stringtruncate(String str, int max)
truncate
if (str.length() <= max) {
    return str;
return str.substring(0, max);
Stringtruncate(String str, int maxLen)
truncates a string regardless of its length.
if (str == null || str.length() < maxLen)
    return str;
if (maxLen < 0)
    return "";
return str.substring(0, maxLen);
Stringtruncate(String str, int maxSize)
Truncate a string to a max size.
if (str == null) {
    return null;
if (str.length() <= maxSize) {
    return str;
return str.substring(0, maxSize);
Stringtruncate(String str, int maxSize)
truncate
if (str != null && maxSize >= 0 && str.length() > maxSize) {
    return str.substring(0, maxSize);
} else {
    return str;
Stringtruncate(String str, int n)
Truncates a string and appends an ellipsis.
return str.length() < n ? str : (str.substring(0, n) + "...");
Stringtruncate(String str, int size, boolean useEllipsis)
Truncate a string to a certain number of characters.
String result = str;
if (str != null && str.length() > size) {
    result = str.substring(0, size);
    if (useEllipsis) {
        result += "...";
return result;
...
Stringtruncate(String str, int start, int end)
Returns the string truncated from the start index to end index.
if (isNullOrEmpty(str)) {
    throw new IllegalArgumentException("Invalid String!, str: " + str);
if (start < 0 || start > end || end > str.length()) {
    throw new StringIndexOutOfBoundsException("Invalid Index!, start: " + start + ", endIndex:" + end);
StringBuilder sBuilder = new StringBuilder(str);
sBuilder.delete(start, end);
...
Stringtruncate(String str, String prefix, String suffix)
truncate
if (str.startsWith(prefix) && str.endsWith(suffix))
    return str.substring(prefix.length(), str.length() - suffix.length());
return str;
Stringtruncate(String string, final int length)
truncate
if (string.length() > length) {
    string = string.substring(0, length);
return string;