Pregunta

I'm relatively new to Objective C and I'm trying to figure out how to efficiently replace a character in a string in the case that I know the index where that character would be.

Basically if S is my string I would like to be able to do this s[i] = 'n' for some i

But this looks quite expensive to me:

NSRange range = NSMakeRange(0,1);
NSString *newString = [S stringByReplacingCharactersInRange:range withString:@"n"];

Is it not ??

¿Fue útil?

Solución

Yes, for replacing one single character, copying the entire string is indeed an overkill. It's not like it would highly affect performance unless this is the bottleneck in your app, called a million times a second, but it still feels better to either use NSMutableString and replaceCharactersInRange:NSMakeRange(0, 1) withString:@"n", or simply fall back to using C strings if speed is essential.

Otros consejos

H2CO3 is right. Use mutable arrays. You could also create a Category to support indexed access to your string:

NSMutableString+Index.h

@interface NSMutableString (Index)
- (void)setObject:(id)anObject atIndexedSubscript:(NSUInteger)idx;
@end

NSMutableString+Index.h

@implementation NSMutableString (Index)
- (void)setObject:(id)anObject atIndexedSubscript:(NSUInteger)idx {
    [self replaceCharactersInRange:NSMakeRange(idx, 1) withString:anObject];
}
@end

Somewhere else:

NSMutableString *str = [[NSMutableString alloc] initWithString:@"abcdef"];
str[2] = @"X";
NSLog(str);

Output:

abXdef

Note: Don't forget to import your Category, where you use the indexed syntax.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top