Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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(" "));

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading