short circuit (un)capitalize if string is already (un)capitalized.

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/lang/trunk@1497829 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Brent Worden 2013-06-28 16:21:09 +00:00
parent a3242c0171
commit f291dea74f
2 changed files with 26 additions and 6 deletions

View File

@ -5581,8 +5581,15 @@ public class StringUtils {
if (str == null || (strLen = str.length()) == 0) { if (str == null || (strLen = str.length()) == 0) {
return str; return str;
} }
char firstChar = str.charAt(0);
if (Character.isTitleCase(firstChar)) {
// already capitalized
return str;
}
return new StringBuilder(strLen) return new StringBuilder(strLen)
.append(Character.toTitleCase(str.charAt(0))) .append(Character.toTitleCase(firstChar))
.append(str.substring(1)) .append(str.substring(1))
.toString(); .toString();
} }
@ -5612,8 +5619,15 @@ public class StringUtils {
if (str == null || (strLen = str.length()) == 0) { if (str == null || (strLen = str.length()) == 0) {
return str; return str;
} }
char firstChar = str.charAt(0);
if (Character.isLowerCase(firstChar)) {
// already uncapitalized
return str;
}
return new StringBuilder(strLen) return new StringBuilder(strLen)
.append(Character.toLowerCase(str.charAt(0))) .append(Character.toLowerCase(firstChar))
.append(str.substring(1)) .append(str.substring(1))
.toString(); .toString();
} }

View File

@ -132,9 +132,15 @@ public class StringUtilsTest {
"", StringUtils.capitalize("") ); "", StringUtils.capitalize("") );
assertEquals("capitalize(single-char-string) failed", assertEquals("capitalize(single-char-string) failed",
"X", StringUtils.capitalize("x") ); "X", StringUtils.capitalize("x") );
assertEquals("capitalize(String) failed",
FOO_CAP, StringUtils.capitalize(FOO_CAP) );
assertEquals("capitalize(string) failed",
FOO_CAP, StringUtils.capitalize(FOO_UNCAP) );
assertEquals("uncapitalize(String) failed", assertEquals("uncapitalize(String) failed",
FOO_UNCAP, StringUtils.uncapitalize(FOO_CAP) ); FOO_UNCAP, StringUtils.uncapitalize(FOO_CAP) );
assertEquals("uncapitalize(string) failed",
FOO_UNCAP, StringUtils.uncapitalize(FOO_UNCAP) );
assertEquals("uncapitalize(empty-string) failed", assertEquals("uncapitalize(empty-string) failed",
"", StringUtils.uncapitalize("") ); "", StringUtils.uncapitalize("") );
assertEquals("uncapitalize(single-char-string) failed", assertEquals("uncapitalize(single-char-string) failed",