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

[util] Add abbreviate method to StringUtils #4164

Merged
merged 1 commit into from
Apr 6, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,25 @@
@NonNullByDefault
public class StringUtils {

/**
* Input string is shortened to the maxwidth, the last 3 chars are replaced by ...
*
* For example: (maxWidth 18) input="openHAB is the greatest ever", return="openHAB is the ..."
*
* @param input input string
* @param maxWidth maxmimum amount of characters to return (including ...)
* @return Abbreviated String
*/
public static @Nullable String abbreviate(final @Nullable String input, final int maxWidth) {
if (input != null) {
if (input.length() < 4 || input.length() <= maxWidth) {
return input;
}
return input.substring(0, maxWidth - 3) + "...";
}
return input;
}

/**
* If a newline char exists at the end of the line, it is removed
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,17 @@
@NonNullByDefault
public class StringUtilsTest {

@Test
public void abbreviateTest() {
assertEquals("", StringUtils.abbreviate("", 10));
assertEquals(null, StringUtils.abbreviate(null, 5));
assertEquals("openHAB is the ...", StringUtils.abbreviate("openHAB is the greatest ever", 18));
assertEquals("four", StringUtils.abbreviate("four", 4));
assertEquals("...", StringUtils.abbreviate("four", 3));
assertEquals("abc", StringUtils.abbreviate("abc", 3));
assertEquals("abc", StringUtils.abbreviate("abc", 2));
}

@Test
public void chompTest() {
assertEquals("", StringUtils.chomp(""));
Expand Down