Given a string say "acbXyzKlm" i want to split it to abc, Xyz,开发者_如何学PythonKlm. One naive way to do this is to go traverse the string and detect the case change to split. I was wondering if there is a better algorithm for this.
To determine if a point in the string is a valid breaking point, you need to have read both characters around breaking point. So any algorithm to solve this will need to analyze the case of every character.
Your algorithm does just that, hence it's computationally optimal. Any "better" algorithm would be a variant and/or micro-optimization of that, with the same overall complexity.
I needed this today, so I implemented it with a category:
@interface NSString (Extensions)
- (NSString*) spacify;
@end
@implementation NSString (Extensions)
- (NSString*) spacify
{
// ignore irrelevant strings
if (self.length < 1)
return self;
NSMutableString* result = [NSMutableString stringWithString:self];
// create a range starting after the first character
NSRange range;
range.location = 1;
range.length = [self length] - 1;
// match any uppercase character
NSRegularExpression* r = [NSRegularExpression regularExpressionWithPattern: @"[A-Z]"
options: 0
error: nil];
// replace matches with the match preceded by a space
[r replaceMatchesInString: result
options: 0
range: range
withTemplate: @" $0"];
return [NSString stringWithString:result];
}
@end
Tests:
@implementation NSStringExtensionsTest
- (void) testSpacify
{
NSString* target = @"ThisIsAStringX";
NSString* expected = @"This Is A String X";
NSString* actual = [target spacify];
STAssertEqualObjects(expected, actual, nil);
}
- (void) testSpacify_NoMatches_DoesNothing
{
NSString* target = @"thisisstring";
NSString* actual = [target spacify];
STAssertEqualObjects(target, actual, nil);
}
- (void) testSpacify_EmptyString_DoesNothing
{
NSString* target = @"";
NSString* actual = [target spacify];
STAssertEqualObjects(target, actual, nil);
}
- (void) testSpacify_InvalidLength_DoesNothing
{
NSString* target = @"A";
NSString* actual = [target spacify];
STAssertEqualObjects(target, actual, nil);
}
@end
精彩评论