[LANG-407] StringUtils.length(String) returns null-safe length.

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/lang/trunk@618882 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Gary D. Gregory 2008-02-06 04:32:56 +00:00
parent 6dd93fc367
commit b0b8356b0b
2 changed files with 22 additions and 0 deletions

View File

@ -4581,6 +4581,18 @@ public class StringUtils {
}
}
/**
* Gets a String's length or <code>0</code> if the String is <code>null</code>.
*
* @param str
* a String or <code>null</code>
* @return String length or <code>0</code> if the String is <code>null</code>.
* @since 2.4
*/
public static int length(String str) {
return str == null ? 0 : str.length();
}
// Centering
//-----------------------------------------------------------------------
/**

View File

@ -1403,6 +1403,15 @@ public class StringUtilsTest extends TestCase {
assertEquals(" abc", StringUtils.leftPad("abc", 5, ""));
}
public void testLength() {
assertEquals(0, StringUtils.length(null));
assertEquals(0, StringUtils.length(""));
assertEquals(0, StringUtils.length(StringUtils.EMPTY));
assertEquals(1, StringUtils.length("A"));
assertEquals(1, StringUtils.length(" "));
assertEquals(8, StringUtils.length("ABCDEFGH"));
}
//-----------------------------------------------------------------------
public void testCenter_StringInt() {
assertEquals(null, StringUtils.center(null, -1));
@ -1647,6 +1656,7 @@ public class StringUtilsTest extends TestCase {
public void testEMPTY() {
assertNotNull(StringUtils.EMPTY);
assertEquals("", StringUtils.EMPTY);
assertEquals(0, StringUtils.EMPTY.length());
}
public void testRemoveStart() {