Search code examples
javastringsnakecase

Convert a String to customised version of Snake case and capitalise first character before every underscore in Java


Suppose I have string like FOO_BAR or foo_bar or Foo_Bar, I want to convert it to customised snake case like below

 FOO_BAR ->   Foo Bar
`foo_bar` -> `Foo Bar`
`Foo_Bar` -> `Foo Bar`

As you can notice all three inputs provide the same output, capitalise the first character before every underscore and first one, and remove the _ (underscore).

Looked into various libraries like guava and apache but as this is customized version couldn't find any Out of the box solution.

Tried below code but and make it work but its looking bit complex

str.replaceAll("([a-z])([A-Z])", "$1_$2").replaceAll("_", " ")

Output of above code is like FOO BAR basically all characters in uppercase, that i can fix in another iteration but looking for something more efficient and simple.


Solution

  • Just for a bit of fun, here is a stream-based answer:

    var answer = Arrays.stream(s.split("_"))
                 .map(i -> i.substring(0, 1).toUpperCase() + i.substring(1).toLowerCase())
                 .collect(Collectors.joining(" "));