From 9a448b8d4f6f144419e8143873a4a4946681afcc Mon Sep 17 00:00:00 2001 From: "ilya (leo)" Date: Wed, 23 Jun 2021 19:31:31 +0300 Subject: [PATCH] Optimizing StringDisplayUtils.trimDisplayLength --- .../progressbar/StringDisplayUtils.java | 19 ++++++++++--------- .../progressbar/EastAsianDisplayTest.java | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+), 9 deletions(-) diff --git a/src/main/java/me/tongfei/progressbar/StringDisplayUtils.java b/src/main/java/me/tongfei/progressbar/StringDisplayUtils.java index 9c364b9..f69c633 100644 --- a/src/main/java/me/tongfei/progressbar/StringDisplayUtils.java +++ b/src/main/java/me/tongfei/progressbar/StringDisplayUtils.java @@ -29,17 +29,18 @@ static int getStringDisplayLength(String s) { } static String trimDisplayLength(String s, int maxDisplayLength) { - StringBuilder sb = new StringBuilder(); - int i = 0; + if (maxDisplayLength <= 0) { + return ""; + } + int totalLength = 0; - while (totalLength < maxDisplayLength) { - char c = s.charAt(i); - totalLength += getCharDisplayLength(c); - if (totalLength > maxDisplayLength) break; - i++; - sb.append(c); + for (int i = 0; i < s.length(); i++) { + totalLength += getCharDisplayLength(s.charAt(i)); + if (totalLength > maxDisplayLength) { + return s.substring(0, i); + } } - return sb.toString(); + return s; } } diff --git a/src/test/java/me/tongfei/progressbar/EastAsianDisplayTest.java b/src/test/java/me/tongfei/progressbar/EastAsianDisplayTest.java index d1df7ed..626602e 100644 --- a/src/test/java/me/tongfei/progressbar/EastAsianDisplayTest.java +++ b/src/test/java/me/tongfei/progressbar/EastAsianDisplayTest.java @@ -17,6 +17,25 @@ void testEastAsianDisplayLength() { assertEquals(StringDisplayUtils.getStringDisplayLength("プログレスバー"), 14); } + @Test + void testEastAsianTrimDisplayLength() { + assertEquals(StringDisplayUtils.trimDisplayLength("Progress bar", 0), ""); + assertEquals(StringDisplayUtils.trimDisplayLength("Progress bar", 10), "Progress b"); + assertEquals(StringDisplayUtils.trimDisplayLength("Progress bar", 15), "Progress bar"); + assertEquals(StringDisplayUtils.trimDisplayLength("进度条", 0), ""); + assertEquals(StringDisplayUtils.trimDisplayLength("进度条", 4), "进度"); + assertEquals(StringDisplayUtils.trimDisplayLength("进度条", 8), "进度条"); + assertEquals(StringDisplayUtils.trimDisplayLength("进度条", 0), ""); + assertEquals(StringDisplayUtils.trimDisplayLength("進度條", 4), "進度"); + assertEquals(StringDisplayUtils.trimDisplayLength("進度條", 8), "進度條"); + assertEquals(StringDisplayUtils.trimDisplayLength("진행 표시줄", 0), ""); + assertEquals(StringDisplayUtils.trimDisplayLength("진행 표시줄", 8), "진행 표"); + assertEquals(StringDisplayUtils.trimDisplayLength("진행 표시줄", 15), "진행 표시줄"); + assertEquals(StringDisplayUtils.trimDisplayLength("プログレスバー", 0), ""); + assertEquals(StringDisplayUtils.trimDisplayLength("プログレスバー", 11), "プログレス"); + assertEquals(StringDisplayUtils.trimDisplayLength("プログレスバー", 18), "プログレスバー"); + } + @Test void testProgressBarsWithEastAsianScript() {