Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 638
Moshe Avatar asked Jul 28 '11 17:07

Moshe


People also ask

What is camelCase conversion?

Camel Case (camelCase) is typography where the first letter of the first word of the sentence is a small letter, and then every first letter of the subsequent words is a capital letter, and the remaining letters of that word are in lower case.

What is Camel Case C++?

CamelCase is a way to separate the words in a phrase by making the first letter of each word capitalized and not using spaces. It is commonly used in web URLs, programming and computer naming conventions. It is named after camels because the capital letters resemble the humps on a camel's back.


1 Answers

- (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.)
like image 160
Evan Mulawski Avatar answered Oct 13 '22 20:10

Evan Mulawski