Created
February 15, 2012 19:59
-
-
Save swillits/1838565 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@interface NSString (A) | |
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target options:(NSStringCompareOptions)options range:(NSRange)searchRange withHandler:(NSString * (^)(NSString * occurrence, NSRange rangeOfString))replaceBlock; | |
@end | |
@implementation NSString (A) | |
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target options:(NSStringCompareOptions)options range:(NSRange)searchRange withHandler:(NSString * (^)(NSString * occurrence, NSRange rangeOfString))replaceBlock; | |
{ | |
NSMutableString * ms = [[self mutableCopy] autorelease]; | |
NSInteger rangeDifference = 0; | |
NSRange foundRange; | |
do { | |
foundRange = [self rangeOfString:target options:options range:searchRange]; | |
if (foundRange.location == NSNotFound) { | |
break; | |
} | |
NSString * foundString = [ms substringWithRange:foundRange]; | |
NSString * replacement = replaceBlock(foundString, foundRange); | |
NSInteger difference = (replacement.length - foundString.length); | |
NSRange rangeInMS = NSMakeRange(foundRange.location + rangeDifference, foundRange.length); | |
[ms replaceCharactersInRange:rangeInMS withString:replacement]; | |
rangeDifference += difference; | |
NSInteger searchRangeDelta = NSMaxRange(foundRange) - searchRange.location; | |
searchRange.location = NSMaxRange(foundRange); | |
searchRange.length -= searchRangeDelta; | |
} while (searchRange.length > 0); | |
return [[ms copy] autorelease]; | |
} | |
@end | |
int main (int argc, const char * argv[]) | |
{ | |
@autoreleasepool { | |
NSString * original = @"The fox ran over the hills and through the woods."; | |
NSString * new = [original stringByReplacingOccurrencesOfString:@"the" options:NSCaseInsensitiveSearch range:NSMakeRange(0, original.length) | |
withHandler:^(NSString *occurrence, NSRange rangeOfString){ | |
if ([occurrence isEqual:@"The"]) return @"Theeeee"; | |
return @"da"; | |
}]; | |
NSLog(@"%@", new); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment