How to convert text to camel case in Objective-C?
- (NSString *)camelCaseFromString:(NSString *)input
{
return [NSString stringWithFormat:@"k%@", [[input capitalizedString]stringByReplacingOccurrencesOfString:@" " withString:@""]];
}
- Capitalize each word.
- Remove whitespace.
- Insert "k" at the beginning. (Not literally, but a simplification using
stringWithFormat
.)
The currently accepted answer has a bug. (also pointed out by @jaydee3)
Words already having proper camelCasing, PascalCasing, or capitalized TLA acronyms will have their correct casing "destroyed" by having non-first characters lowercased via the call to capitalizedString
.
So "I prefer camelCasing to PascalCasing for variables"
would look like "iPreferCamelcasingToPascalcasingForVariables" but according to the question, should be "iPreferCamelCasingToPascalCasingForVariables"
Use the below category on NSString to create non-destructive camel and pascal casing. It also properly leaves ALL_CAPS words/acronyms in place, although that wasn't really part of the orig question.
An acronym as a first word for a camelCased string would be weird. "WTH"
becomes "wTH"
which looks weird. Anyway, that's an edge case, and not addressed. However, since question asker is prefixing with "k" then it "k IBM"
becomes "kIBM"
which looks ok to me, but would look be "kIbm"
with currently accepted answer.
Use:
NSString *str = @"K computer manufacturer IBM";
NSLog(@"constant: %@", str.pascalCased);
// "constant: kComputerManufacturerIBM"
Category (class extension) code.
@implementation NSString (MixedCasing)
- (NSString *)camelCased {
NSMutableString *result = [NSMutableString new];
NSArray *words = [self componentsSeparatedByString: @" "];
for (uint i = 0; i < words.count; i++) {
if (i==0) {
[result appendString:((NSString *) words[i]).withLowercasedFirstChar];
}
else {
[result appendString:((NSString *)words[i]).withUppercasedFirstChar];
}
}
return result;
}
- (NSString *)pascalCased {
NSMutableString *result = [NSMutableString new];
NSArray *words = [self componentsSeparatedByString: @" "];
for (NSString *word in words) {
[result appendString:word.withUppercasedFirstChar];
}
return result;
}
- (NSString *)withUppercasedFirstChar {
if (self.length <= 1) {
return self.uppercaseString;
} else {
return [NSString stringWithFormat:@"%@%@",[[self substringToIndex:1] uppercaseString],[self substringFromIndex:1]];
}
}
- (NSString *)withLowercasedFirstChar {
if (self.length <= 1) {
return self.lowercaseString;
} else {
return [NSString stringWithFormat:@"%@%@",[[self substringToIndex:1] lowercaseString],[self substringFromIndex:1]];
}
}
@end