我有一个字符串@"DidNotTurnUp"
。我想写一个函数,它将此字符串作为输入,并应输出@"Did Not Turn Up"
。最好的方法是什么?如何基于大写字母分隔字符串中的单词?帮助赞赏。
答案 0 :(得分:3)
这是NSString上的一个类别,可以做你想要的。
@implementation NSString (SeparateCapitalizedWords)
-(NSString*)stringBySeparatingCapitalizedWords
{
static NSRegularExpression * __regex ;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSError * error = nil ;
__regex = [ NSRegularExpression regularExpressionWithPattern:@"[\\p{Uppercase Letter}]" options:0 error:&error ] ;
if ( error ) { @throw error ; }
});
NSString * result = [ __regex stringByReplacingMatchesInString:self options:0 range:(NSRange){ 1, self.length - 1 } withTemplate:@" $0" ] ;
return result ;
}
@end
答案 1 :(得分:1)
试试这个
NSString *YourString=@"YouAreAGoodBoy";
NSString *outString;
NSString *string=@"";
NSUInteger length = [YourString length];
for (NSUInteger i = 0; i < length; i++)
{
char c = [YourString characterAtIndex:i];
if (i > 0 && c >= 65 && c <=90)
{
outString=[NSString stringWithFormat:@"%C", c];
string = [NSString stringWithFormat:@"%@%@%@",string,@" ",outString];
}
else
{
outString=[NSString stringWithFormat:@"%C", c];
string = [NSString stringWithFormat:@"%@%@",string,outString];
}
}
NSLog(@"%@",string);
希望此代码对您有用。
答案 2 :(得分:0)
NSString *string = @"ThisStringIsJoined";
NSRegularExpression *regexp = [NSRegularExpression
regularExpressionWithPattern:@"([a-z])([A-Z])"
options:0
error:NULL];
NSString *newString = [regexp
stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, string.length)
withTemplate:@"$1 $2"];
NSLog(@"Changed '%@' -> '%@'", string, newString);