NSMutableString insertString atIndex
- (void)insertString:(NSString *)aString atIndex:(NSUInteger)anIndex
Parameters
aString
The string to insert into the receiver. aString must not be nil.
anIndex
The location at which aString is inserted. The location must not exceed the bounds of the receiver.
Important: Raises an NSRangeException if anIndex lies beyond the end of the string.
Discussion of [NSMutableString insertString atIndex]
The new characters begin at anIndex and the existing characters from anIndex to the end are shifted by the length of aString.
This method treats the length of the string as a valid index value that returns an empty string.
NSMutableString insertString atIndex example.
NSString *s = @"abcdefghijklmnop";
NSMutableString *mu = [NSMutableString stringWithString:s];
[mu insertString:@" || " atIndex:5];
// This is one option
s = [mu copy];
//[(id)s insertString:@"er" atIndex:7]; This will crash your app because s is not mutable
// This is an other option
s = [NSString stringWithString:mu];
// The Following code is not good
s = mu;
[mu replaceCharactersInRange:NSMakeRange(0, [mu length]) withString:@"Changed string!!!"];
NSLog(@" s == %@ : while mu == %@ ", s, mu);
// ----> Not good because the output is the following line
// s == Changed string!!! : while mu == Changed string!!!
NSMutableString *mu = [NSMutableString stringWithString:s];
[mu insertString:@" || " atIndex:5];
// This is one option
s = [mu copy];
//[(id)s insertString:@"er" atIndex:7]; This will crash your app because s is not mutable
// This is an other option
s = [NSString stringWithString:mu];
// The Following code is not good
s = mu;
[mu replaceCharactersInRange:NSMakeRange(0, [mu length]) withString:@"Changed string!!!"];
NSLog(@" s == %@ : while mu == %@ ", s, mu);
// ----> Not good because the output is the following line
// s == Changed string!!! : while mu == Changed string!!!
Example of [NSMutableString insertString atIndex].
You need a mutable string, not a NSString.
NSMutableString *str = [NSMutableString stringWithString:old_string];
[str insertString:@"-" atIndex:8];
[str insertString:@"-" atIndex:4];
NSMutableString *str = [NSMutableString stringWithString:old_string];
[str insertString:@"-" atIndex:8];
[str insertString:@"-" atIndex:4];
NSMutableString insertString atIndex example.
NSMutableString * mutable = [NSMutableString stringWithString:@"05-8-2012"];
[mutable insertString:@"0" atIndex:3];
NSLog(@"my day is:%@",mutable);
[mutable insertString:@"0" atIndex:3];
NSLog(@"my day is:%@",mutable);