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

StringtruncateByCharLength(String string, int maxLength)
truncate By Char Length
return string.length() > maxLength ? string.substring(0, maxLength) : string;
StringtruncateByCharLengthWithEllipsis(String string, int maxLength)
truncate By Char Length With Ellipsis
return string.length() <= maxLength ? string : truncateByCharLength(string, maxLength - 3) + "...";
StringtruncateCellValue(String x, int maxChars)
truncate Cell Value
if (x.length() > maxChars) {
    return x.substring(0, Math.max(3, maxChars)) + " ...";
} else {
    return x;
StringtruncateCodeStringIfNeeded(String codeString)
truncate Code String If Needed
if (codeString != null && codeString.length() > CODE_LENGTH) {
    return codeString.substring(0, CODE_LENGTH);
} else {
    return codeString;
StringtruncateData(String data, int idLength)
truncate Data
String truncateData = data;
if (data != null && data.length() > idLength) {
    truncateData = data.substring(0, (idLength - 1));
return truncateData;
StringtruncateDatabaseName(String db)
truncate Database Name
if (db.length() <= 27) {
    return db;
int underscoreIndex = db.indexOf("_");
String genusLetter = db.substring(0, 1);
String result = genusLetter + "_" + db.substring(underscoreIndex + 1);
if (result.length() > 27) {
    result = result.replaceAll("otherfeatures", "other...");
...
StringtruncatedStr(String s, int maxLength)
Truncates s string if it is longer than maxLength .
if (s.length() <= maxLength)
    return s;
else
    return s.substring(0, maxLength);
StringtruncateExtension(String name)
Truncates the extension of the file name.
return name.lastIndexOf('.') == -1 ? name : name.substring(0, name.lastIndexOf('.'));
StringtruncateFileName(String agent, String s)
Used for parsing uploaded file names.
if (agent == null) {
    return s;
} else {
    if (agent.contains("MSIE")) {
        if (s.contains("\\")) {
            int pos = s.lastIndexOf("\\");
            return s.substring(pos + 1);
        } else {
...
StringtruncateFileType(String p)
truncate File Type
int indexOfPeriod = p.lastIndexOf(".");
if (indexOfPeriod < 0)
    return p;
else {
    return p.substring(0, indexOfPeriod);