changing characters in string

Discussion in 'Mac Programming' started by saurabh1jadhav, Oct 30, 2009.

  1. macrumors newbie

    Joined:
    Sep 22, 2009
    #1
    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??
     
  2. macrumors 6502a

    GorillaPaws

    Joined:
    Oct 26, 2003
    Location:
    Richmond, VA
    #2
    You need to use an NSMutableString.
     
  3. macrumors 68030

    jared_kipe

    Joined:
    Dec 8, 2003
    Location:
    Seattle
    #3
    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 stringWithStringinputString];
         
    NSRange secondPos NSMakeRange);
         
    NSRange fourthPos NSMakeRange);

         
    NSString *secondSub = [inputString substringWithRangesecondPos];
         
    NSString *fourthSub = [inputString substringWithRangefourthPos];

         [
    workingString replaceCharactersInRangefourthPos withStringsecondSub];
         [
    workingString replaceCharactersInRangesecondPos withStringfourthSub];

         
    // 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
     

Share This Page