Added additional trim methods for Strings

This commit is contained in:
Patrick Gotthard 2014-04-18 18:37:28 +02:00
parent 5f65787ca5
commit 94104fd50d
2 changed files with 59 additions and 1 deletions

View file

@ -48,7 +48,7 @@ public final class Strings {
}
/**
* null-safe trimming of a String.
* Removes the whitespace at the beginning and end of a String.
*
* @param s The String to trim, may be null
* @return null when the input String is null, the trimmed String otherwise
@ -61,6 +61,36 @@ public final class Strings {
}
}
/**
* Removes the whitespace at the beginning and end of a String. When the String only contains whitespace, it returns null.
*
* @param s The String to trim, may be null
* @return null when the input String is null or does only contain whitespace, the trimmed String otherwise
*/
public static String trimToNull(final String s) {
final String trimmed = trim(s);
if (trimmed == null || trimmed.isEmpty()) {
return null;
} else {
return trimmed;
}
}
/**
* Removes the whitespace at the beginning and end of a String. When the String only contains whitespace, it returns null.
*
* @param s The String to trim, may be null
* @return null when the input String is null or does only contain whitespace, the trimmed String otherwise
*/
public static String trimToEmpty(final String s) {
final String trimmed = trim(s);
if (trimmed == null || trimmed.isEmpty()) {
return "";
} else {
return trimmed;
}
}
/**
* null-safe lower-case conversion of a String.
*

View file

@ -80,6 +80,34 @@ public class StringsTest {
assertThat(Strings.trim(string), is("a"));
}
@Test
public void testTrimToEmpty() {
final String nullString = null;
final String emptyString = "";
final String blankString = " ";
final String string = " a ";
assertThat(Strings.trimToEmpty(nullString), is(""));
assertThat(Strings.trimToEmpty(emptyString), is(""));
assertThat(Strings.trimToEmpty(blankString), is(""));
assertThat(Strings.trimToEmpty(string), is("a"));
}
@Test
public void testTrimToNull() {
final String nullString = null;
final String emptyString = "";
final String blankString = " ";
final String string = " a ";
assertThat(Strings.trimToNull(nullString), is(nullValue()));
assertThat(Strings.trimToNull(emptyString), is(nullValue()));
assertThat(Strings.trimToNull(blankString), is(nullValue()));
assertThat(Strings.trimToNull(string), is("a"));
}
@Test
public void testToLowerCase() {