格式化 NSString,Objective-C
Formatting NSString, Objective-C
像这样转换 NSString 的最佳方法是什么(大小写混合)
@"Hello lorem ipsum";
@"i am a test";
给这些(没有空格的驼峰式大小写)
@"helloLoremIpsum";
@"iAmATest";
这太过分了,但是 TransformerKit has a bunch of NSValueTransformers
that can be used, one is for camel casing. The relevant file is TTTStringTransformers.m 如果您想构建自己的轻便解决方案。
试试这个
使用 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
像这样转换 NSString 的最佳方法是什么(大小写混合)
@"Hello lorem ipsum";
@"i am a test";
给这些(没有空格的驼峰式大小写)
@"helloLoremIpsum";
@"iAmATest";
这太过分了,但是 TransformerKit has a bunch of NSValueTransformers
that can be used, one is for camel casing. The relevant file is TTTStringTransformers.m 如果您想构建自己的轻便解决方案。
试试这个
使用 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