Guava tips: Strings

Guava contains the simple, yet very useful class Strings, with some useful methods to help you work with strings. Notable among them are:

  • nullToEmpty: given a String, returns it if it’s not null and the empty string "" otherwise. Useful to sanitize inputs when you don’t know whether the caller will use empty strings or null.
  • isNullOrEmpty: given a String, returns true if it is null or the empty string "".

Some other useful methods are:

  • padStart and padEnd, which can be used to ensure that a given string has a minimum length by adding characters to them.
  • commonPrefix and commonSuffix, which return the longest common prefix or suffix of two strings.
  • repeat, which simply returns n copies of the given string.

Here are some (pretty trivial) examples:

assertEquals("abc", Strings.nullToEmpty("abc"));
assertEquals("", Strings.nullToEmpty(""));
assertEquals("", Strings.nullToEmpty(null));

assertFalse(Strings.isNullOrEmpty("abc"));
assertTrue(Strings.isNullOrEmpty(""));
assertTrue(Strings.isNullOrEmpty(null));

assertEquals("0014", Strings.padStart("14", 4, '0'));
assertEquals("15", Strings.padStart("15", 2, '0'));
assertEquals("AB ", Strings.padEnd("AB", 3, ' '));

assertEquals("AB", Strings.commonPrefix("ABC", "ABDEF"));
assertEquals("", Strings.commonPrefix("ABC", "DEF"));
assertEquals("DE", Strings.commonSuffix("ABCDE", "XDE"));

assertEquals("ababab", Strings.repeat("ab", 3));
assertEquals("ab", Strings.repeat("ab", 1));
assertEquals("", Strings.repeat("ab", 0));