From befff2625bf6183b9a94a02d5163a5aa732c6b25 Mon Sep 17 00:00:00 2001 From: Francesca Guiducci Date: Thu, 19 Oct 2017 12:42:13 -0700 Subject: [PATCH] Add startCase function (#94) --- src/main/java/strman/Strman.java | 15 +++++++++++++++ src/test/java/strman/StrmanTests.java | 18 ++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/main/java/strman/Strman.java b/src/main/java/strman/Strman.java index 6598b0b..b66f717 100644 --- a/src/main/java/strman/Strman.java +++ b/src/main/java/strman/Strman.java @@ -1404,6 +1404,21 @@ public static String[] chop(String input, int step) { .toArray(String[]::new); } + /** + * Converts a String into its Start Case version + * https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage + * + * @param input The input String + * @return Start Case String + */ + public static String startCase(final String input) { + validate(input, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER); + // split into a word when we encounter a space, or an underscore, or a dash, or a switch from lower to upper case + String[] words = words(input, "\\s|_|-|(?<=[a-z])(?=[A-Z])"); + return Arrays.stream(words).filter(w -> !w.trim().isEmpty()) + .map(w -> upperFirst(w.toLowerCase())).collect(joining(" ")); + } + private static void validate(String value, Predicate predicate, final Supplier supplier) { if (predicate.test(value)) { throw new IllegalArgumentException(supplier.get()); diff --git a/src/test/java/strman/StrmanTests.java b/src/test/java/strman/StrmanTests.java index ae7b88e..c5ea9bc 100644 --- a/src/test/java/strman/StrmanTests.java +++ b/src/test/java/strman/StrmanTests.java @@ -1186,4 +1186,22 @@ public void chop_shouldChopStringByStep() throws Exception { assertThat(chop("whitespace", 3).length, equalTo(4)); assertThat(chop("whitespace", 0)[0].length(), equalTo(10)); } + + @Test(expected = IllegalArgumentException.class) + public void startCase_shouldThrowException() throws Exception { + startCase(null); + } + + @Test + public void startCase_shouldStartCaseInputString() throws Exception { + assertThat(startCase(""), equalTo("")); + assertThat(startCase("ALL CAPS"), equalTo("All Caps")); + assertThat(startCase("camelCase"), equalTo("Camel Case")); + assertThat(startCase("kebab-case"), equalTo("Kebab Case")); + assertThat(startCase("Snake_case"), equalTo("Snake Case")); + assertThat(startCase(" spaces "), equalTo("Spaces")); + assertThat(startCase("spaces between words"), equalTo("Spaces Between Words")); + assertThat(startCase("--dashes--"), equalTo("Dashes")); + assertThat(startCase("dashes----between----words"), equalTo("Dashes Between Words")); + } }