Convert String to Camel Case Using Java


The challenge

Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).

Examples

toCamelCase("the-stealth-warrior"); // returns "theStealthWarrior"

toCamelCase("The_Stealth_Warrior"); // returns "TheStealthWarrior"

Test cases

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest {
    @Test
    public void testSomeUnderscoreLowerStart() {
      String input = "the_Stealth_Warrior";
      System.out.println("input: "+input);      
      assertEquals("theStealthWarrior", Solution.toCamelCase(input));
    }
    @Test
    public void testSomeDashLowerStart() {
      String input = "the-Stealth-Warrior";
      System.out.println("input: "+input);      
      assertEquals("theStealthWarrior", Solution.toCamelCase(input));
    }
}

The solution in Java

import java.lang.StringBuilder;
class Solution{

  // Our method
  static String toCamelCase(String s){

    // create a StringBuilder to create our output string
    StringBuilder sb = new StringBuilder();
    
    // determine when the next capital letter will be
    Boolean nextCapital = false;

    // loop through the string
    for (int i=0; i<s.length(); i++) {

      // if the current character is a letter
      if (Character.isLetter(s.charAt(i))) {

        // get the current character
        char tmp = s.charAt(i);

        // make it a capital if required
        if (nextCapital) tmp = Character.toUpperCase(tmp);

        // add it to our output string
        sb.append(tmp);

        // make sure the next character isn't a capital
        nextCapital = false;

      } else {
        // otherwise the next letter should be a capital
        nextCapital = true;
      }
    }
    
    // return our output string
    return sb.toString();
  }
}