ellipsize method
截断字符
text处理文体
length
最大长度(以字符计)
endChars
末尾显示字符
isAccurate
是否精确统计
Implementation
String ellipsize(int length, String endChars, bool isAccurate) {
String text = this?.trim() ?? "";
int len = text.length;
int count = 0;
StringBuffer builder = new StringBuffer();
for (int i = 0; i < len; i++) {
var c = text.substring(i, i + 1);
if (isAccurate && RegExp("[\u4e00-\u9fa5]").hasMatch(c)) {
count += 2;
} else {
count++;
}
if (count <= length) {
builder.write(c);
} else {
break;
}
}
if (len >= length) {
builder.write(endChars);
}
return builder.toString().trim();
}