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!!!