我的要求是根据某些条件截断具有最大计数的字符串。条件是,
- 字符串的长度不应超过最大计数
- 它不应该以半字结尾
I want to trun
- 字符串的结尾应由 中的以下任何一个字符决定
{" ",".",",",";",":","-","。","、",":",",",";"}
,并且该字符必须替换为...
对于上述要求,我编写了代码,但是当字符串有两个连续的字符(如,
和)时它会失败;
。我的代码如下,
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
}
由于我是 JAVA 世界的新手,因此为糟糕的代码道歉...... :)
提前致谢。干杯!!!