Fixed #28. Added support for safeTruncate function

This commit is contained in:
Shekhar Gulati
2016-05-21 23:56:51 +05:30
parent 18b0f0ae19
commit 162b02bf98
2 changed files with 46 additions and 0 deletions
+31
View File
@@ -812,6 +812,37 @@ public abstract class Strman {
return value.replaceAll("\\s+$", "");
}
/**
* Truncate the string securely, not cutting a word in half. It always returns the last full word.
*
* @param value The input String
* @param length Max size of the truncated String
* @param filler String that will be added to the end of the return string. Example: '...'
* @return The truncated String
*/
public static String safeTruncate(final String value, final int length, final String filler) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
if (length == 0) {
return "";
}
if (length >= value.length()) {
return value;
}
String[] words = value.split("\\W+");
StringJoiner result = new StringJoiner(" ");
int spaceCount = 0;
for (String word : words) {
if (result.length() + word.length() + filler.length() + spaceCount > length) {
break;
} else {
result.add(word);
spaceCount++;
}
}
return append(result.toString(), filler);
}
public static String decode(final String value, final int digits, final int radix) {
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
return Arrays
+15
View File
@@ -619,4 +619,19 @@ public class StrmanTest {
assertThat(rightTrim(" strman"), equalTo(" strman"));
assertThat(rightTrim("strman"), equalTo("strman"));
}
@Test
public void safeTruncate_shouldSafelyTruncateStrings() throws Exception {
assertThat(safeTruncate("foo bar", 0, "."), equalTo(""));
assertThat(safeTruncate("foo bar", 4, "."), equalTo("foo."));
assertThat(safeTruncate("foo bar", 3, "."), equalTo("."));
assertThat(safeTruncate("foo bar", 2, "."), equalTo("."));
assertThat(safeTruncate("foo bar", 7, "."), equalTo("foo bar"));
assertThat(safeTruncate("foo bar", 8, "."), equalTo("foo bar"));
assertThat(safeTruncate("A Javascript string manipulation library.", 16, "..."), equalTo("A Javascript..."));
assertThat(safeTruncate("A Javascript string manipulation library.", 15, "..."), equalTo("A Javascript..."));
assertThat(safeTruncate("A Javascript string manipulation library.", 14, "..."), equalTo("A..."));
assertThat(safeTruncate("A Javascript string manipulation library.", 13, "..."), equalTo("A..."));
}
}