Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CamelCase to underscores and back in Objective-C

I'm looking for a simple, efficient way to convert strings in CamelCase to underscore notation (i.e., MyClassName -> my_class_name) and back again in Objective C.

My current solution involves lots of rangeOfString, characterAtIndex, and replaceCharactersInRange operations on NSMutableStrings, and is just plain ugly as hell :) It seems that there must be a better solution, but I'm not sure what it is.

I'd rather not import a regex library just for this one use case, though that is an option if all else fails.

like image 557
John Biesnecker Avatar asked Dec 17 '09 01:12

John Biesnecker


1 Answers

Chris's suggestion of RegexKitLite is good. It's an excellent toolkit, but this could be done pretty easily with NSScanner. Use -scanCharactersFromSet:intoString: alternating between +uppercaseLetterCharacterSet and +lowercaseLetterCharacterSet. For going back, you'd use -scanUpToCharactersFromSet: instead, using a character set with just an underscore in it.

like image 82
Rob Napier Avatar answered Sep 21 '22 05:09

Rob Napier