Skip to content

Commit

Permalink
Add abbreviate method (#4164)
Browse files Browse the repository at this point in the history
Signed-off-by: Leo Siepel <leosiepel@gmail.com>
  • Loading branch information
lsiepel committed Apr 6, 2024
1 parent 875ebaa commit f18c50f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
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

0 comments on commit f18c50f

Please sign in to comment.