View Full Version : changing characters in string

Oct 30, 2009, 07:39 AM
i have a NSString *Str=@"macintosh". i want that 4th character should be in 2nd place and 2nd character in 4th place.(i.e. manctosh). How to do this??

Oct 30, 2009, 07:45 AM
You need to use an NSMutableString.

Oct 30, 2009, 11:29 AM
Obviously you need the computer to do it for you because you cannot, (i.e. your example removes the letter i, but doesn't move it or the a). :rolleyes:

-(NSString *) secondToFourth: (NSString *) inputString {
if ([inputString length] < 4) {
return nil;

NSMutableString *workingString = [NSMutableString stringWithString: inputString];
NSRange secondPos = NSMakeRange( 1 , 1 );
NSRange fourthPos = NSMakeRange( 3 , 1 );

NSString *secondSub = [inputString substringWithRange: secondPos];
NSString *fourthSub = [inputString substringWithRange: fourthPos];

[workingString replaceCharactersInRange: fourthPos withString: secondSub];
[workingString replaceCharactersInRange: secondPos withString: fourthSub];

// all objects are autoreleased, including the returned one
// this may not work on wider text encodings ;) but I don't care
return workingString;

EDIT: added some exception checking