views:

1366

answers:

4

The title pretty much says it all. What's the simplest/most elegant way that I can convert, in Java, a string from the format "THIS_IS_AN_EXAMPLE_STRING" to the format "ThisIsAnExampleString"? I figure there must be at least one way to do it using String.replaceAll() and a regex, but I've really never understood Java regexes. My initial thoughts are: prepend the string with an underscore (_), convert the whole string to lower case, and then use replaceAll to convert every character preceded by an underscore with its uppercase version.

+5  A: 
static String toCamelCase(String s){
   String[] parts = s.split("_");
   String camelCaseString = "";
   for (String part : parts){
      camelCaseString = camelCaseString + toProperCase(part);
   }
   return camelCaseString;
}

static String toProperCase(String s) {
    return s.substring(0, 1).toUpperCase() +
               s.substring(1).toLowerCase();
}

Note: You need to add argument validation.

C. Ross
Nice answer, but it would be a little better if either the method name described the fact that the string was split or that logic was externalised and the method calls aligned as a pipe, e.g. "THIS_IS_AN_EXAMPLE_STRING".removeUnderscores().toCamelCase()This is more reusable.
Dan Gravell
That's not necessarily *better* (though yes, it is more reusable). When it comes to name formatting conventions, camelcase can/does imply not using underscores; on the reverse side of the coin, there are conventions which specify using underscores. So in my mind, this is just a method to convert from one format to another.
Matt Ball
+2  A: 
String input = "ABC_DEF";
StringBuilder sb = new StringBuilder;
for( String oneString : input.split("_") )
{
    sb.append( oneString.substring(0,1) );
    sb.append( oneString.substring(1).toLowerCase() );
}

//sb now holds your desired string
Alex B
+12  A: 

Take a look at WordUtils in the Apache Commons lang library: http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/WordUtils.html

Specifically, the capitalizeFully(String str, char[] delimiters) method should do the job:

String blah = "LORD_OF_THE_RINGS";
assertEquals("LordOfTheRings", WordUtils.capitalizeFully(blah, new char[]{'_'}).replaceAll("_", ""));

Green bar!

Dan Gravell
No sir! We should rewrite these existing, already-working utilities ourselves, for we are proper programmers!
skaffman
It's 16:42 on a Friday afternoon. I'll let everyone else rewrite it, I'm going out for a beer \o/ ;)
Dan Gravell
"Proper" programmers? Allow me... http://xkcd.com/378/
Matt Ball
More to the point, I don't even have access to that particular package with my current setup, and since I really don't (yet) need anything beyond the capitalizeFully method, I lose nothing by writing it myself.
Matt Ball
I respect your decision Matt, it's probably the right thing to do in your position. However, consider the following:* Someone else in your team decides they need a routine to swap the case of letters. They implement it. You now have ~20 lines to maintain. You would have ~2 if you used the library. And don't forget the unit tests!* The accepted answer has a downside in that the method name does not describe what the code does. A well reused API like the commons stuff rarely has those downsides.The point is that maintenance is the biggest cost of software. Generally, re-use is a good idea.
Dan Gravell
+1  A: 
public static void main(String[] args) {
    String start = "THIS_IS_A_TEST";
    StringBuffer sb = new StringBuffer();
    for (String s : start.split("_")) {
        sb.append(Character.toUpperCase(s.charAt(0)));
        if (s.length() > 1) {
            sb.append(s.substring(1, s.length()).toLowerCase());
        }
    }
    System.out.println(sb);
}
Yishai