格式化NSString,Objective-C

时间:2017-04-27 13:51:11

标签: objective-c nsstring

转换像这样的NSStrings的最佳方法是什么(混合大小写)

@"Hello lorem ipsum";
@"i am a test";

这些(没有空格的驼峰案例)

@"helloLoremIpsum";
@"iAmATest";

2 个答案:

答案 0 :(得分:2)

试试这个

使用For循环

- (NSString *)camelCased:(NSString *)aString  {
    NSMutableString *result = [NSMutableString new];
    NSArray *words = [aString componentsSeparatedByString: @" "];
    for (NSUInteger i = 0; i < words.count; i++) {
        if (i==0) {
            [result appendString:([words[i] lowercaseString])];
        }
        else {
            [result appendString:([words[i] capitalizedString])];
        }
    }
    return result;
}

使用阻止

- (NSString *)camelCasedUsingBlock:(NSString *)aString  {
    NSMutableArray *words = [[NSMutableArray alloc] init];
    [[aString componentsSeparatedByString:@" "] enumerateObjectsUsingBlock:^(id anObject, NSUInteger idx, BOOL *stop) {
        if (idx == 0) {
            [words addObject:[anObject lowercaseString]];
        }
        else{
            [words addObject:[anObject capitalizedString]];
        }
    }];
    return [words componentsJoinedByString:@""];
}

NSLog(@"%@",[self camelCased:@"Hello lorem ipsum"]);//helloLoremIpsum
NSLog(@"%@",[self camelCased:@"i am a test"]);//iAmATest

答案 1 :(得分:0)

它有点矫枉过正,但是TransformerKit有一堆<body> <div class="container"> <header> <h1>Comment Box</h1> <form class="new-resolution"> <input type="text" name="title" placeholder="Enter comment..."> <input type="submit" value="Submit" id="submit"> </form> </header> </div> </body>可以使用,一个用于骆驼套管。如果您想为轻盈构建自己的解决方案,则相关文件为TTTStringTransformers.m