Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimizing StringDisplayUtils.trimDisplayLength #104

Merged
merged 1 commit into from
Jul 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions src/main/java/me/tongfei/progressbar/StringDisplayUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

}
19 changes: 19 additions & 0 deletions src/test/java/me/tongfei/progressbar/EastAsianDisplayTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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() {

Expand Down