Skip to content
Advertisement

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

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.

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.

Advertisement

Answer

Another option is using Google Guava’s com.google.common.base.CaseFormat

George Hawkins left a comment with this example of usage:

CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, "THIS_IS_AN_EXAMPLE_STRING");
Advertisement