CamelCase 下划线并返回到 Objective-C [英] CamelCase to underscores and back in Objective-C
问题描述
我正在寻找一种简单有效的方法将 CamelCase 中的字符串转换为下划线符号(即 MyClassName -> my_class_name),然后在 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.
我当前的解决方案涉及 NSMutableStrings 上的大量 rangeOfString
、characterAtIndex
和 replaceCharactersInRange
操作,而且非常丑陋:)似乎必须有更好的解决方案,但我不确定它是什么.
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.
推荐答案
Chris 对 RegexKitLite 的建议很好.这是一个出色的工具包,但可以通过 NSScanner.使用 -scanCharactersFromSet:intoString:
在 +uppercaseLetterCharacterSet
和 +lowercaseLetterCharacterSet
之间交替使用.返回时,您将使用 -scanUpToCharactersFromSet:
代替,使用其中只有一个下划线的字符集.
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.
这篇关于CamelCase 下划线并返回到 Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!