这是可以执行您想要的操作的代码,已更新以处理数字:
NSString *original = @"My computer is on fire at 9:00 AM! What should I do?";
NSString *swapString = @"boss";
NSMutableString *modified = [NSMutableString stringWithCapacity:[original length]];
__block NSUInteger lastCharOffset = 0;
[original enumerateSubstringsInRange:NSMakeRange(0, [original length]) options:NSStringEnumerationByWords // NSStringEnumerationByComposedCharacterSequences // | NSStringEnumerationSubstringNotRequired
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop)
{
//NSLog(@"SUBSTRING %@", substring);
NSString *replaceString = substring;
if([substring length] > 2) {
unichar origChar = [substring characterAtIndex:0];
if(![[NSCharacterSet decimalDigitCharacterSet] characterIsMember:origChar]) {
replaceString = [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:origChar] ? [swapString capitalizedString] : swapString;
}
}
if(substringRange.location) {
[modified appendString:[original substringWithRange:NSMakeRange(lastCharOffset, substringRange.location-lastCharOffset)]];
}
[modified appendString:replaceString];
lastCharOffset = substringRange.location + substringRange.length;
} ];
// Grab any trailing punctuation
[modified appendString:[original substringWithRange:NSMakeRange(lastCharOffset, [original length] - lastCharOffset)]];
NSLog(@"Orig: %@", original);
NSLog(@"Modi: %@", modified);
输出是:
Orig: My computer is on fire at 9:00 AM! What should I do?
Modi: My boss is on boss at 9:00 AM! Boss boss I do?