我得到了一个字符串,我必须将其转换为Camel Case并使用main中的调用从函数返回结果值。
// CaseMaker.h
- (instancetype)initWithString:(NSString *)string;
- (NSString *)process;
@end
// main.m
#import "CaseMaker.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
CaseMaker *maker1 = [[CaseMaker alloc] initWithString:@"this is a string"];
NSLog(@"%@", [maker1 process]);
CaseMaker *maker2 = [[CaseMaker alloc] initWithString:@"loopy lighthouse"];
NSLog(@"%@", [maker2 process]);
}
return 0;
}
我已经能够将带有空格的字符串转换为大写字符,但是我无法将第一个字符转换为小写,而且我将大写的单词字符串大写了,我不想这样做。 NSString的文档并没有我希望的那么有用
.m
- (NSString *)camelCaseFromString:(NSString *)input
{
return [[input capitalizedString]stringByReplacingOccurrencesOfString:@" " withString:@""];
}
主要
CaseMaker *maker1 = [[CaseMaker alloc] camelCaseFromString:@"this is a string"];
NSLog(@"%@", maker1);
CaseMaker *maker2 = [[CaseMaker alloc] camelCaseFromString:@"loopy lighthouse"];
NSLog(@"%@", maker2);
CaseMaker *maker3 = [[CaseMaker alloc] camelCaseFromString:@"supercalifragalisticexpialidocious"];
NSLog(@"%@", maker3);
CaseMaker *maker4 = [[CaseMaker alloc]camelCaseFromString:@"HELLO BRO"];
NSLog(@"%@",maker4);
thisIsAString
loopy灯塔
超定律expexpidoidocious
以上是此作业的预期输出。我在谷歌浏览器周围,看看别人是如何做到这一点的,但是却什么也没找到,阅读了一些关于NSString大写/小写方法的客观c文档,并且仍然对如何处理感到迷惑< / p>
答案 0 :(得分:0)
这里有一个NSString类别,它添加了一个toCamelCase
方法。
NSString + Util.h:
#import <Foundation/Foundation.h>
@interface NSString(Util)
@property (readonly, copy) NSString *camelcaseString;
@end
NSString + Util.m:
#import "NSString+Util.h"
@implementation NSString(Util)
- (NSString *)camelcaseString {
NSMutableString *res = [NSMutableString string];
[[self componentsSeparatedByString:@" "] enumerateObjectsUsingBlock:^(NSString * _Nonnull string, NSUInteger idx, BOOL * _Nonnull stop) {
[res appendString:idx == 0 ? [string lowercaseString] : [string capitalizedString]];
}];
return [res copy];
}
@end
用法:
NSLog(@"%@", @"this is a string".camelcaseString);
输出:
thisIsAString
在Swift中,您可以创建StringProtocol
的扩展名:
extension StringProtocol {
var camelcased: String {
return components(separatedBy: " ").enumerated().map { $0 == 0 ? $1.lowercased() : $1.capitalized }.joined(separator: "")
}
}
用法:
print("this is a string".camelcased)