Sunday, June 2, 2013

NSMutableString replaceCharactersInRange example in Objective C (iOS).


NSMutableString replaceCharactersInRange

Replaces the characters from aRange with those in aString.

- (void)replaceCharactersInRange:(NSRange)aRange withString:(NSString *)aString

Parameters
aRange
The range of characters to replace. aRange must not exceed the bounds of the receiver.
Important: Raises an NSRangeException if any part of aRange lies beyond the end of the receiver.
aString
The string with which to replace the characters in aRange. aString must not be nil.

Discussion of [NSMutableString replaceCharactersInRange]
This method treats the length of the string as a valid range value that returns an empty string.

NSMutableString replaceCharactersInRange example.
NSMutableString *s = [NSMutableString stringWithString:@"/abc asdfpjklwe /abc"];

NSRange a = [s rangeOfString:@"/abc"];
NSRange b = [s rangeOfString:@"/abc" options:NSBackwardsSearch];

if ((a.location == NSNotFound) || (b.location == NSNotFound))  {
    // at least one of the substrings not present
} else {
    [s replaceCharactersInRange:a withString:@"/xyz"];
    [s replaceCharactersInRange:b withString:@"/xyz"];
}

Example of [NSMutableString replaceCharactersInRange].
-(void) swapCharacters: (NSMutableString *) set first: (NSInteger) first second: (NSInteger) second    {

NSLog(@"swap: set = '%@', first = '%d', second = '%d'", set, first, second);
NSRange rangeSecond = NSMakeRange((NSUInteger) second, 1);
NSRange rangeFirst = NSMakeRange((NSUInteger) first, 1);

[set replaceCharactersInRange:rangeSecond withString:[set substringWithRange:rangeFirst]];
}

NSMutableString replaceCharactersInRange example.
NSMutableString *reversed = [original mutableCopyWithZone:NULL];
NSUInteger i, length;

length = [reversed length];

for (i = 0; i < length / 2; i++) {
    // Store the first character as we're going to replace with the character at the end
    // in the example, it would store 'h'
    unichar startChar = [reversed characterAtIndex:i];

    // Only make the end range once
    NSRange endRange = NSMakeRange(length - i, 1);

    // Replace the first character ('h') with the last character ('i')
    // so reversed now contains "ii"
    [reversed replaceCharactersInRange:NSMakeRange(i, 1)
                            withString:[reversed subStringWithRange:endRange];

    // Replace the last character ('i') with the stored first character ('h)
    // so reversed now contains "ih"
    [reversed replaceCharactersInRange:endRange
                            withString:[NSString stringWithFormat:@"%c", startChar]];
}

End of NSMutableString replaceCharactersInRange example article.