From 643eaa1d261a84c21a5d63cc457e35564cc32808 Mon Sep 17 00:00:00 2001 From: Sascha Bieberstein Date: Thu, 25 Apr 2024 10:42:39 +0200 Subject: [PATCH] Allow to capitalize strings via the string cleanup utility --- .../java/sirius/kernel/commons/StringCleanup.java | 14 ++++++++++++++ .../kotlin/sirius/kernel/commons/StringsTest.kt | 12 ++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/main/java/sirius/kernel/commons/StringCleanup.java b/src/main/java/sirius/kernel/commons/StringCleanup.java index bb97b9f1..3995d52b 100644 --- a/src/main/java/sirius/kernel/commons/StringCleanup.java +++ b/src/main/java/sirius/kernel/commons/StringCleanup.java @@ -462,6 +462,20 @@ public static String uppercase(@Nonnull String input) { return input.toUpperCase(); } + /** + * Capitalizes the first character of the given string. + * + * @param input the input to process + * @return the resulting string + */ + public static String capitalize(@Nonnull String input) { + char titleCasedChar = Character.toTitleCase(input.charAt(0)); + if (titleCasedChar == input.charAt(0)) { + return input; + } + return titleCasedChar + input.substring(1); + } + /** * Removes all {@linkplain #PATTERN_STRIP_XML XML tags} from the given string. * diff --git a/src/test/kotlin/sirius/kernel/commons/StringsTest.kt b/src/test/kotlin/sirius/kernel/commons/StringsTest.kt index 3c605700..3fd77e31 100644 --- a/src/test/kotlin/sirius/kernel/commons/StringsTest.kt +++ b/src/test/kotlin/sirius/kernel/commons/StringsTest.kt @@ -203,6 +203,18 @@ class StringsTest { UnaryOperator { term: String? -> StringCleanup.reduceCharacters(term) }, UnaryOperator { input: String? -> StringCleanup.uppercase(input!!) }) ) + assertEquals( + "Hello", + Strings.cleanup("hello", UnaryOperator { input: String? -> StringCleanup.capitalize(input!!) }) + ) + assertEquals( + "HeLLo", + Strings.cleanup("heLLo", UnaryOperator { input: String? -> StringCleanup.capitalize(input!!) }) + ) + assertEquals( + "-hello-", + Strings.cleanup("-hello-", UnaryOperator { input: String? -> StringCleanup.capitalize(input!!) }) + ) assertEquals( "Hello", Strings.cleanup("Hel-lo", UnaryOperator { input: String? -> StringCleanup.removePunctuation(input!!) })