Skip to content

Commit f217246

Browse files
committed
feat[string]: add truncate method to StringUtils
1 parent e6d35b0 commit f217246

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

protocol/src/main/java/com/zfoo/protocol/util/StringUtils.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,25 @@ public static String substringAfterLast(final String str, final String separator
323323
return str.substring(pos + separator.length());
324324
}
325325

326+
public static String truncate(CharSequence charSequence) {
327+
return truncate(charSequence, 18);
328+
}
329+
330+
/**
331+
* Truncate the supplied {@link CharSequence}.
332+
* <p>If the length of the {@code CharSequence} is greater than the threshold,
333+
* this method returns a {@linkplain CharSequence#subSequence(int, int) subsequence} of the {@code CharSequence} (up to the threshold) appended
334+
* with the suffix {@code "..."}. Otherwise, this method returns {@code charSequence.toString()}.
335+
* @param charSequence the {@code CharSequence} to truncate
336+
* @param threshold the maximum length after which to truncate; must be a positive number
337+
* @return a truncated string, or a string representation of the original
338+
*/
339+
public static String truncate(CharSequence charSequence, int threshold) {
340+
if (charSequence.length() > threshold) {
341+
return charSequence.subSequence(0, threshold) + "...";
342+
}
343+
return charSequence.toString();
344+
}
326345

327346
// Replacing
328347
//-----------------------------------------------------------------------

0 commit comments

Comments
 (0)