このようなものは正しい方向へのプッシュである必要があります:
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];
}
アップデート
質問に対するカレブの編集をフォローしたい場合は、これを使用して置換された文字列を置き換えることができます。
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];
}