实现说明
逻辑集中在类 TruncateEllipsis和函数 truncate、main里。
文件的主干是一个循环——for (String sample : samples)。
使用要点
- 执行文件,
main会按顺序走完truncate。
常见问题
「在码点边界截断文本」这个示例怎么运行?
把它当完整程序编译/解释运行即可——不需要先安装任何东西。
主签名形如 static String truncate(String text, int codePointLimit)
核心语句
return text.substring(0, cutOffset) + "…";
代码示例
public class TruncateEllipsis {
// cut on a code point boundary, never inside a surrogate pair
static String truncate(String text, int codePointLimit) {
if (text.codePointCount(0, text.length()) <= codePointLimit) {
return text;
}
int cutOffset = text.offsetByCodePoints(0, codePointLimit - 1);
return text.substring(0, cutOffset) + "…";
}
public static void main(String[] args) {
String[] samples = {
"abcdefghij",
"café déjà vu",
"🚀🚀🚀🚀🚀",
"short"};
for (String sample : samples) {
String cut = truncate(sample, 6);
System.out.println(sample + " (" + sample.codePointCount(0, sample.length())
+ " code points) -> " + cut
+ " (" + cut.codePointCount(0, cut.length()) + " code points)");
}
}
}