Skip to content

Instantly share code, notes, and snippets.

@decagondev
Last active January 29, 2025 22:50
Show Gist options
  • Select an option

  • Save decagondev/dc3e31b4d92277e267a1618d425f2524 to your computer and use it in GitHub Desktop.

Select an option

Save decagondev/dc3e31b4d92277e267a1618d425f2524 to your computer and use it in GitHub Desktop.

Problem Statement

Create a method or function that converts dash (-) or underscore (_) delimited words into camel case. The solution must handle capitalization according to the rules below:

  • The first word in the output should only be capitalized if the original word was capitalized (this is known as Upper Camel Case or Pascal Case).
  • Every word after the first should always have its first letter capitalized.

Examples

Input Output
"the-stealth-warrior" "theStealthWarrior"
"The_Stealth_Warrior" "TheStealthWarrior"
"The_Stealth-Warrior" "TheStealthWarrior"

Solution Explanation

Step-by-Step Breakdown

  1. Split the Phrase:

    • Break the input text into separate words wherever you see a dash (-) or underscore (_).
  2. Handle the First Word:

    • Keep the first word exactly as it appears without changing its capitalization.
  3. Capitalize Following Words:

    • For every word after the first:
      • Capitalize the first letter.
      • Leave the remaining letters in lowercase.
  4. Combine the Words:

    • Join the words together without any spaces, dashes, or underscores.

Example Walkthroughs

Example 1: "the-stealth-warrior"

  1. Split: ["the", "stealth", "warrior"]
  2. First Word: Keep "the" as is.
  3. Capitalize Following Words: ["the", "Stealth", "Warrior"]
  4. Join: "theStealthWarrior"

Example 2: "The_Stealth_Warrior"

  1. Split: ["The", "Stealth", "Warrior"]
  2. First Word: Keep "The" as is.
  3. Capitalize Following Words: Already capitalized.
  4. Join: "TheStealthWarrior"

Example 3: "The_Stealth-Warrior"

  1. Split: ["The", "Stealth", "Warrior"]
  2. First Word: Keep "The" as is.
  3. Capitalize Following Words: Already capitalized.
  4. Join: "TheStealthWarrior"

Naïve Algorithm in Java (Commented Version)

// Step 1: Define a method to convert a string to camel case
// Example: "the-stealth-warrior" -> "theStealthWarrior"

// Step 2: Split the input string by both dash (-) and underscore (_) delimiters
// Use a regular expression to capture both delimiters
// Example: "the-stealth-warrior" becomes ["the", "stealth", "warrior"]

// Step 3: Initialize an empty StringBuilder to build the result

// Step 4: Handle the first word
// - Append it as is to the result without changing its capitalization

// Step 5: Loop through the remaining words
// - For each word, capitalize the first letter and keep the rest lowercase
// - Append the transformed word to the result

// Step 6: Return the final combined string from the StringBuilder

// Example Java implementation outline:
// public String toCamelCase(String input) {
//     // Step 2: Split by dash or underscore
//     String[] words = input.split("[-_]");
//     StringBuilder result = new StringBuilder();

//     // Step 4: Handle the first word
//     if (words.length > 0) {
//         result.append(words[0]);
//     }

//     // Step 5: Handle the remaining words
//     for (int i = 1; i < words.length; i++) {
//         String word = words[i];
//         if (word.length() > 0) {
//             result.append(Character.toUpperCase(word.charAt(0)));
//             result.append(word.substring(1).toLowerCase());
//         }
//     }

//     // Step 6: Return the result
//     return result.toString();
// }

Optimized Algorithm in Java (Commented Version)

// Step 1: Define an optimized method to convert a string to camel case
// The main improvement is to reduce memory operations and optimize string handling

// Step 2: Check for empty or null input as an edge case
// Return an empty string if the input is null or empty

// Step 3: Split the input string by dash (-) or underscore (_) delimiters using a regular expression
// Example: "the-stealth-warrior" becomes ["the", "stealth", "warrior"]

// Step 4: Use a StringBuilder initialized with a sensible capacity to reduce memory resizing

// Step 5: Append the first word directly without altering its case

// Step 6: Loop through the remaining words efficiently
// - Skip empty words caused by consecutive delimiters
// - Append the uppercase first letter and lowercase remaining letters

// Step 7: Return the final combined string directly from StringBuilder

// Example Java implementation outline:
// public String toCamelCaseOptimized(String input) {
//     if (input == null || input.isEmpty()) {
//         return "";
//     }

//     String[] words = input.split("[-_]");
//     StringBuilder result = new StringBuilder(input.length()); // Optimized capacity

//     if (words.length > 0) {
//         result.append(words[0]); // Append the first word as is
//     }

//     for (int i = 1; i < words.length; i++) {
//         String word = words[i];
//         if (!word.isEmpty()) { // Skip empty segments
//             result.append(Character.toUpperCase(word.charAt(0)))
//                   .append(word.substring(1).toLowerCase());
//         }
//     }

//     return result.toString();
// }

Regular Expression-Based Algorithm in Java (Commented Version)

// Step 1: Define a method using regular expressions to convert to camel case
// Regular expressions will efficiently locate and replace delimiters and adjacent characters

// Step 2: Use a regex pattern to match any dash or underscore followed by a letter
// Example pattern: "[-_](.)" captures the letter after a dash or underscore

// Step 3: Apply a regex replacement function to capitalize matched characters
// For example, "-w" becomes "W" using a function replacement

// Step 4: Ensure the first word retains its original capitalization
// Return the transformed string directly

// Example Java implementation outline:
// public String toCamelCaseRegex(String input) {
//     if (input == null || input.isEmpty()) {
//         return "";
//     }

//     // Use a regular expression to find delimiters and capitalize the next letter
//     String result = input.replaceAll("[-_](.)", match -> match.group(1).toUpperCase());

//     return result;
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment