CamelCase 下划线并返回到 Objective-C [英] CamelCase to underscores and back in Objective-C

查看:48
本文介绍了CamelCase 下划线并返回到 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 上的大量 rangeOfStringcharacterAtIndexreplaceCharactersInRange 操作,而且非常丑陋:)似乎必须有更好的解决方案,但我不确定它是什么.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆