![](/img/trans.png)
[英]How do I convert an NSString from CamelCase to TitleCase, 'playerName' into 'Player Name'?
[英]How do I convert a string to camelcase
我有一個字符串,我必須轉換為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
loopyLighthouse
supercalifragalisticexpialidocious
以上是此分配的預期輸出。 我正在谷歌周圍看看其他人如何接近這個,但實際上找不到任何東西,閱讀一些關於NSString的大寫/小寫方法的客觀c文檔,並仍然對如何繼續
這是一個添加toCamelCase
方法的NSString類。
的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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.