Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

saurabh1jadhav

macrumors newbie
Original poster
Sep 22, 2009
1
0
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??
 
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:

PHP:
-(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
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.