My requirement is to truncate the string with max count and based on some conditions. The conditions are,
- The length of the string should not exceed the max count
- It should not end with half word like
I want to trun - The end of the string should be decided by any one of the following character in
{" ",".",",",";",":","-","。","、",":",",",";"}, and the character has to be replaced with...
For the above requirement I write the code, but it fails when the string have two consecutive characters like , and ; . My code follows,
public String getTruncateText(String text, int count) {
int textLength = text.length();
String truncatedText = text.substring(0, Math.min(count, textLength)).trim();
int index = StringUtils.lastIndexOfAny(truncatedText,
new String[] {" ",".",",",";",":","-","。","、",":",",",";"});
return truncatedText.substring(0, index > 0 ? index : truncatedText.length()) + "...";
}
@Test
public void Test() {
String text = "I want to truncate text, Test";
assertThat(getTruncateText(text, 15)).isEqualTo("I want to..."); //Success
assertThat(getTruncateText(text, 25)).isEqualTo("I want to truncate text..."); //Success
assertThat(getTruncateText(text, 1)).isEqualTo("I..."); //Success
assertThat(getTruncateText(text, 2)).isEqualTo("I..."); //Success
assertThat(getTruncateText(text, 300)).isEqualTo("I want to truncate text..."); //Failed
}
Since I am new to JAVA world, apologies for the bad code... :)
Thanks in advance. Cheers!!!
You might needStringUtil.LastIndexOfAnyButwhich returns the index of the last character that is NOT in a given set of characters.I have fixed the solution, and there are several things to point out here.
Originally, you used
index > 0here, however, when index=0, "..." is supposed to be return, butindex > 0will cause it to go to the else branch, giving the length of the text as the end index and returning the full string instead.Having done some research, I found that people DID try to implement
lastIndexOfAnyButfor the library, but it has never been added to any released version. For more information, you can check out this thread.So I use
indexOfAnyButinstead on the reversedtruncatedTextto find the first occurence of a non-ending character before the ending character (e.g. "I want to truncate text, Test"). Note thatString.joinis used here asindexOfAnyButdoesn't accept String[] as the second argument.