This commit is contained in:
Looly 2023-06-30 10:29:05 +08:00
parent 566c43d464
commit 63c1c7ab93
2 changed files with 37 additions and 1 deletions

View File

@ -3188,6 +3188,18 @@ public class CharSequenceUtil extends StrValidator {
return sub(string, 0, length) + "...";
}
/**
* 截断字符串使用UTF8编码为字节后不超过maxBytes长度
*
* @param str 原始字符串
* @param maxBytesLength 最大字节数
* @param appendDots 截断后是否追加省略号(...)
* @return 限制后的长度
*/
public static String limitByteLengthUtf8(final String str, final int maxBytesLength, final boolean appendDots) {
return limitByteLength(str, CharsetUtil.UTF_8, maxBytesLength, 4, appendDots);
}
/**
* 截断字符串使用其按照指定编码为字节后不超过maxBytes长度
*

View File

@ -287,9 +287,33 @@ public class CharSequenceUtilTest {
@Test
void codeLengthTest() {
String a = "🍒🐽";
final String a = "🍒🐽";
final int i = StrUtil.codeLength(a);
Assertions.assertEquals(4, a.length());
Assertions.assertEquals(2, i);
}
@Test
public void limitByteLengthUtf8Test() {
final String str = "这是This一段中英文";
String ret = StrUtil.limitByteLengthUtf8(str, 12, true);
Assertions.assertEquals("这是Thi...", ret);
ret = StrUtil.limitByteLengthUtf8(str, 13, true);
Assertions.assertEquals("这是This...", ret);
ret = StrUtil.limitByteLengthUtf8(str, 14, true);
Assertions.assertEquals("这是This...", ret);
ret = StrUtil.limitByteLengthUtf8(str, 999, true);
Assertions.assertEquals(str, ret);
}
@Test
public void limitByteLengthTest() {
final String str = "This is English";
final String ret = StrUtil.limitByteLength(str, CharsetUtil.ISO_8859_1,10, 1, false);
Assertions.assertEquals("This is En", ret);
}
}