From 032a4ce087f240631b6d2ada9bfe0b2c4542da25 Mon Sep 17 00:00:00 2001 From: Fabian Becker Date: Sat, 1 Nov 2014 13:27:09 +0100 Subject: [PATCH] Added new convertToUnderscore method. --- src/eva2/tools/StringTools.java | 38 ++++++++++++++++++++++++++++ test/eva2/tools/StringToolsTest.java | 31 ++++++++++++++++++++--- 2 files changed, 65 insertions(+), 4 deletions(-) diff --git a/src/eva2/tools/StringTools.java b/src/eva2/tools/StringTools.java index f1a7ed00..c22379fc 100644 --- a/src/eva2/tools/StringTools.java +++ b/src/eva2/tools/StringTools.java @@ -429,6 +429,44 @@ public final class StringTools { return upcaseFirst(word); } + /** + * Converts a camelCase to a more human form, with spaces. + * E.g. 'Camel Case'. + * + * @param word Word to convert to a readable String + * @return Readable String representation of input word + */ + public static String convertToUnderscore(final String word) { + Pattern pattern = Pattern.compile("([A-Z]|[a-z])[a-z]*"); + + List tokens = new ArrayList<>(); + Matcher matcher = pattern.matcher(word); + String acronym = ""; + while (matcher.find()) { + String found = matcher.group(); + if (found.matches("^[A-Z]$")) { + acronym += found; + } else { + if (acronym.length() > 0) { + //we have an acronym to add before we continue + tokens.add(acronym); + acronym = ""; + } + tokens.add(found); + } + } + + if (acronym.length() > 0) { + tokens.add(acronym); + } + + if (!tokens.isEmpty()) { + return concatFields(tokens, "-").toLowerCase(); + } + + return word.toLowerCase(); + } + /** * Takes a string and returns it with the first character * converted to uppercase. diff --git a/test/eva2/tools/StringToolsTest.java b/test/eva2/tools/StringToolsTest.java index daf3b350..6fc7419b 100644 --- a/test/eva2/tools/StringToolsTest.java +++ b/test/eva2/tools/StringToolsTest.java @@ -1,13 +1,14 @@ package eva2.tools; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; import org.junit.After; -import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + /** * * @author becker @@ -47,6 +48,28 @@ public class StringToolsTest { } } + /** + * Test of humaniseCamelCase method, of class StringTools. + */ + @Test + public void testConvertToUnderscore() { + HashMap map = new HashMap<>(); + map.put("camelCase", "camel-case"); + map.put("CamelCase", "camel-case"); + map.put("thisIsAwesome", "this-is-awesome"); + map.put("THQIsNice", "thq-is-nice"); + map.put("iLikeABC", "i-like-abc"); + + String key, value; + for (Object o : map.entrySet()) { + Map.Entry pairs = (Map.Entry) o; + key = (String) pairs.getKey(); + value = (String) pairs.getValue(); + String result = StringTools.convertToUnderscore(key); + assertEquals(value, result); + } + } + /** * Test of upcaseFirst method, of class StringTools. */