How to convert CamelCase into human-readable names in Java?

How to convert CamelCase into human-readable names in Java?

To convert CamelCase strings into human-readable names in Java, you can use regular expressions and string manipulation. Here's a Java function that accomplishes this:

import java.util.regex.Matcher; import java.util.regex.Pattern; public class CamelCaseToHumanReadable { public static String convert(String camelCase) { // Define a regular expression pattern to match capital letters Pattern pattern = Pattern.compile("[A-Z][a-z]*"); // Use the pattern to find all matching substrings in the CamelCase string Matcher matcher = pattern.matcher(camelCase); // Create a StringBuilder to build the human-readable name StringBuilder result = new StringBuilder(); // Iterate through the matches and append them to the result while (matcher.find()) { if (result.length() > 0) { result.append(" "); // Add a space between words } result.append(matcher.group()); } return result.toString(); } public static void main(String[] args) { String camelCase = "camelCaseExample"; String humanReadable = convert(camelCase); System.out.println(humanReadable); // Output: "camel Case Example" } } 

In this example:

  1. We define a regular expression pattern [A-Z][a-z]* to match capital letters followed by zero or more lowercase letters. This pattern is used to identify the words in the CamelCase string.

  2. We use Pattern.matcher() to create a Matcher object for the input CamelCase string.

  3. We iterate through the matches using matcher.find() and append each matched word to a StringBuilder. We add a space between words to create the human-readable format.

  4. Finally, we return the resulting StringBuilder as a string.

When you run the convert method with a CamelCase input, it will convert it into a human-readable format with spaces between the words.


More Tags

xaml apache-storm kendo-ui-angular2 android-relativelayout dynamics-crm-online pow jbutton .net-standard-2.0 var mediatr

More Java Questions

More Mortgage and Real Estate Calculators

More Internet Calculators

More Biology Calculators

More Mixtures and solutions Calculators