|
1 | 1 | /*
|
2 |
| - * Copyright 2002-2022 the original author or authors. |
| 2 | + * Copyright 2002-2023 the original author or authors. |
3 | 3 | *
|
4 | 4 | * Licensed under the Apache License, Version 2.0 (the "License");
|
5 | 5 | * you may not use this file except in compliance with the License.
|
@@ -75,6 +75,10 @@ public abstract class StringUtils {
|
75 | 75 |
|
76 | 76 | private static final char EXTENSION_SEPARATOR = '.';
|
77 | 77 |
|
| 78 | + private static final int DEFAULT_TRUNCATION_THRESHOLD = 100; |
| 79 | + |
| 80 | + private static final String TRUNCATION_SUFFIX = " (truncated)..."; |
| 81 | + |
78 | 82 |
|
79 | 83 | //---------------------------------------------------------------------
|
80 | 84 | // General convenience methods for working with Strings
|
@@ -1388,4 +1392,40 @@ public static String arrayToCommaDelimitedString(@Nullable Object[] arr) {
|
1388 | 1392 | return arrayToDelimitedString(arr, ",");
|
1389 | 1393 | }
|
1390 | 1394 |
|
| 1395 | + /** |
| 1396 | + * Truncate the supplied {@link CharSequence}. |
| 1397 | + * <p>Delegates to {@link #truncate(CharSequence, int)}, supplying {@code 100} |
| 1398 | + * as the threshold. |
| 1399 | + * @param charSequence the {@code CharSequence} to truncate |
| 1400 | + * @return a truncated string, or a string representation of the original |
| 1401 | + * {@code CharSequence} if its length does not exceed the threshold |
| 1402 | + * @since 5.3.27 |
| 1403 | + */ |
| 1404 | + public static String truncate(CharSequence charSequence) { |
| 1405 | + return truncate(charSequence, DEFAULT_TRUNCATION_THRESHOLD); |
| 1406 | + } |
| 1407 | + |
| 1408 | + /** |
| 1409 | + * Truncate the supplied {@link CharSequence}. |
| 1410 | + * <p>If the length of the {@code CharSequence} is greater than the threshold, |
| 1411 | + * this method returns a {@linkplain CharSequence#subSequence(int, int) |
| 1412 | + * subsequence} of the {@code CharSequence} (up to the threshold) appended |
| 1413 | + * with the suffix {@code " (truncated)..."}. Otherwise, this method returns |
| 1414 | + * {@code charSequence.toString()}. |
| 1415 | + * @param charSequence the {@code CharSequence} to truncate |
| 1416 | + * @param threshold the maximum length after which to truncate; must be a |
| 1417 | + * positive number |
| 1418 | + * @return a truncated string, or a string representation of the original |
| 1419 | + * {@code CharSequence} if its length does not exceed the threshold |
| 1420 | + * @since 5.3.27 |
| 1421 | + */ |
| 1422 | + public static String truncate(CharSequence charSequence, int threshold) { |
| 1423 | + Assert.isTrue(threshold > 0, |
| 1424 | + () -> "Truncation threshold must be a positive number: " + threshold); |
| 1425 | + if (charSequence.length() > threshold) { |
| 1426 | + return charSequence.subSequence(0, threshold) + TRUNCATION_SUFFIX; |
| 1427 | + } |
| 1428 | + return charSequence.toString(); |
| 1429 | + } |
| 1430 | + |
1391 | 1431 | }
|
0 commit comments