驼峰命名与蛇形(下划线)命名的互转

在使用数据库(FMDB)时,读取数据库字段名时发现读出来的全部是小写,而创建表时是按照驼峰命名(传进去的是model),这样会造成查询不到数据

使用下面两个方法可以实现两种名字的互换

 1 //驼峰名字转下划线名字
 2 -(NSString *)translateToInsertName:(NSString *)name
 3 {
 4     NSMutableString *insertName = [name mutableCopy];
 5     
 6     for(int i = 0; i < name.length; i++)
 7     {
 8         char c = [insertName characterAtIndex:i];
 9         if(c>64 && c<91)
10         {
11             NSRange range = NSMakeRange(i, 1);
12             [insertName replaceCharactersInRange:range withString:[NSString stringWithFormat:@"_%@", [[NSString stringWithFormat:@"%c",c] lowercaseString]]];
13         }
14     }
15     return insertName;
16 }
17 
18 //下划线名字转驼峰名字
19 -(NSString *)translateToOutPutName:(NSString *)name
20 {
21     NSMutableString *outputName = [NSMutableString stringWithString:name];
22     while ([outputName containsString:@"_"]) {
23         NSRange range = [outputName rangeOfString:@"_"];
24         if (range.location + 1 < [outputName length]) {
25             char c = [outputName characterAtIndex:range.location+1];
26             [outputName replaceCharactersInRange:NSMakeRange(range.location, range.length+1) withString:[[NSString stringWithFormat:@"%c",c] uppercaseString]];
27         }
28     }
29     return outputName;
30 }

如有错误,还望不吝指教!

******

后面的内容与标题无关 推广下个人开发的APP 觉得还不错的 自己自己偷偷用就行了

密码口袋

原文地址:https://www.cnblogs.com/PaulpauL/p/6143645.html