Apex Convert String To Camel Case

Convert string to camelCase for one underscore

   public static String toCamelCase(String input) {
      Pattern p = Pattern.compile('_([a-zA-Z])');
      Matcher m = p.matcher( input );
      fflib_StringBuilder sb = new fflib_StringBuilder();
      while (m.find()) {
          sb.add(m.replaceAll(m.group(1).toUpperCase()));
      }
      return sb.toString().uncapitalize();
     }

Convert string to camelCase for multiple underscore

 public static String toCamelCase(String input){
      fflib_StringBuilder sb = new fflib_StringBuilder();
      boolean capitalizeNext = false;
      for (String c:input.split('')) {
        if (c == '_') {
          capitalizeNext = true;
        } else {
          if (capitalizeNext) {
            sb.add(c.toUpperCase());
            capitalizeNext = false;
          } else {
            sb.add(c.toLowerCase());
          }
        }
      }
      return sb.toString();
    }

To Camel Case Test Class

@isTest
	static void testToCamelCase(){
		Test.startTest();
			System.assertEquals(BrightPlan_Rest_Util.toCamelCase('loan_id'), 'loanId');
			System.assertEquals(BrightPlan_Rest_Util.toCamelCase('Camel_case_This_word'), 'camelCaseThisWord');
			System.assertEquals(BrightPlan_Rest_Util.toCamelCase('this_IS_A_TEst_for_CAMEL_Case'), 'thisIsATestForCamelCase');
		Test.stopTest();
	}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: