|
| 1 | +package easy; |
| 2 | + |
| 3 | +/** |
| 4 | + * Have the function CamelCase(str) take the str parameter being passed |
| 5 | + * and return it in proper camel case format where the first letter |
| 6 | + * of each word is capitalized (excluding the first letter). |
| 7 | + * --- |
| 8 | + * The string will only contain letters and some combination of delimiter |
| 9 | + * punctuation characters separating each word. |
| 10 | + * For example: if str is "BOB loves-coding" then your program |
| 11 | + * should return the string bobLovesCoding. |
| 12 | + */ |
| 13 | +public class CamelCase { |
| 14 | + |
| 15 | + /** |
| 16 | + * A helper function which removes non-alphabetic characters, |
| 17 | + * converts to a lower case and trims the string. |
| 18 | + * |
| 19 | + * @param str input string |
| 20 | + * @return a string with non-alphabetic characters removed |
| 21 | + */ |
| 22 | + private static String[] splitWords(String str) { |
| 23 | + return str |
| 24 | + .toLowerCase() |
| 25 | + .replaceAll("([^a-z])", " ") |
| 26 | + .replaceAll(" +", " ") |
| 27 | + .trim().split(" "); |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * Camel Case function. |
| 32 | + * |
| 33 | + * @param str input string |
| 34 | + * @return a string in proper camel case format |
| 35 | + */ |
| 36 | + private static String camelCase(String str) { |
| 37 | + StringBuilder camel = new StringBuilder(); |
| 38 | + String[] words = splitWords(str); |
| 39 | + int index = 0; |
| 40 | + for (String word : words) { |
| 41 | + if (index == 0) { |
| 42 | + camel.append(word); |
| 43 | + } else { |
| 44 | + camel.append(word.substring(0, 1).toUpperCase()).append(word.substring(1)); |
| 45 | + } |
| 46 | + index++; |
| 47 | + } |
| 48 | + return camel.toString(); |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Entry point. |
| 53 | + * |
| 54 | + * @param args command line arguments |
| 55 | + */ |
| 56 | + public static void main(String[] args) { |
| 57 | + var result1 = camelCase("_good_looking_blues_"); |
| 58 | + System.out.println(result1); |
| 59 | + |
| 60 | + var result2 = camelCase("-=last-night-on-earth=-"); |
| 61 | + System.out.println(result2); |
| 62 | + |
| 63 | + } |
| 64 | + |
| 65 | +} |
0 commit comments