像这样的事情应该是朝着正确的方向推动:
static NSString * StringByReplacingEverySecondOccurrenceWithString(
NSString * const pSource,
NSString * const pSearch,
NSString * const pReplace)
{
/* @todo test that pSource has two occurrences before copying, and return [pSource.copy autorelease] if false. */
NSMutableString * const str = [pSource.mutableCopy autorelease];
bool isEven = true;
for (NSUInteger pos = 0; pos < str.length; isEven = !isEven) {
const NSRange remainder = NSMakeRange(pos, str.length - pos);
const NSRange next = [str rangeOfString:pSearch options:0 range:remainder];
if (NSNotFound != next.location && !isEven) {
[str replaceCharactersInRange:next withString:pReplace];
}
pos = next.location + next.length;
}
return [str.copy autorelease];
}
更新
如果您想按照 Caleb 对问题的编辑,您可以使用它来替换替换字符串:
static NSString * StringByReplacingWithAlternatingStrings(
NSString * const pSource,
NSString * const pSearch,
NSString * const pReplaceA,
NSString * const pReplaceB)
{
/* @todo test that pSource has two occurrences before copying, and return [pSource.copy autorelease] if false. */
NSMutableString * const str = [pSource.mutableCopy autorelease];
bool isEven = true;
for (NSUInteger pos = 0; pos < str.length; isEven = !isEven) {
const NSRange remainder = NSMakeRange(pos, str.length - pos);
const NSRange next = [str rangeOfString:pSearch options:0 range:remainder];
if (NSNotFound != next.location) {
NSString * const substitution = isEven ? pReplaceA : pReplaceB;
[str replaceCharactersInRange:next withString:substitution];
pos = next.location + substitution.length;
}
else {
pos = NSNotFound;
}
}
return [str.copy autorelease];
}