Search code examples
objective-ccstring-formatting

How to convert text to camel case in Objective-C?


I'm making little utility to help me generate code for an app I'm making. I like to have constants for my NSUserDefaults settings, so that my code is more readable and easier to maintain. The problem is, that making constants for everything takes some time, so I'm trying to write a utility to generate code for me. I'd like to be able to enter a string and have it converted to camel case, like so:

- (NSString *)camelCaseFromString:(NSString *)input{
    return inputAsCamelCase;
}

Now, the input string might be composed of multiple words. I'm assuming that I need some sort of regular expression here, or perhaps there is another way to do it. I'd like to input something like this:

@"scrolling direction"

or this:

@"speed of scrolling"

and get back something like this:

kScrollingDirection

or this:

kSpeedOfScrolling

How would you go about removing spaces and replacing the character following the space with the uppercase version?


Solution

  • - (NSString *)camelCaseFromString:(NSString *)input {
        return [@"k" stringByAppendingString:[[input capitalizedString] stringByReplacingOccurrencesOfString:@" " withString:@""]];
    }
    
    1. Capitalize each word.
    2. Remove whitespace.
    3. Insert "k" at the beginning. (Not literally, but a simplification using stringByAppendingString.)