-1

I am trying to replace an array of characters from within an NSString.

For example if we have this string:

NSString *s = @"number one and two and three";
NSArray  *A1 = [NSArray arrayWithObjects:@"one",@"two",@"three", nil];
NSArray  *A2 = [NSArray arrayWithObjects:@"1",@"2",@"3", nil];

I need to replace all members of that string found within A1 with the corresponding members of A2.

Till
  • 27,559
  • 13
  • 88
  • 122
Fawaz
  • 584
  • 1
  • 11
  • 24

1 Answers1

3

NSString has an instance method called stringByReplacingOccurencesOfString: see the Apple Documentation for NSString for help on the actual method - code wise you could try the below code.

NSString *s = @"number one and two and three";
NSArray  *A1 = [NSArray arrayWithObjects:@"one",@"two",@"three", nil];
NSArray  *A2 = [NSArray arrayWithObjects:@"1",@"2",@"3", nil];

NSLog(@"s before : %@", s);
// Logs "s before : number one and two and three"

// Lets check to make sure that the arrays are the same length first if not forget about replacing the strings.
if([A1 count] == [A2 count]) {
    // Goes into a for loop for based on the number of objects in A1 array
    for(int i = 0; i < [A1 count]; i++) {
        // Get the object at index i from A1 and check string "s" for that objects value and replace with object at index i from A2. 
       if([[A1 objectAtIndex:i] isKindOfClass:[NSString class]] 
           && [[A2 objectAtIndex:i] isKindOfClass:[NSString class]]) {
           // If statement to check that the objects at index are both strings otherwise forget about it.
           s = [s stringByReplacingOccurrencesOfString:[A1 objectAtIndex:i] withString:[A2 objectAtIndex:i]]; 
       } 
    }
}

NSLog(@"s after : %@", s);
// Logs "s after : number 1 and 2 and 3"

As noted in comments this code could return "bone" as "b1". To get around this you could I suppose replace your arrays with:

NSArray  *A1 = [NSArray arrayWithObjects:@" one ",@" two ",@" three ", nil];
NSArray  *A2 = [NSArray arrayWithObjects:@" 1 ",@" 2 ",@" 3 ", nil];

Note I all I have done is added in the spaces so if you had "bone" it will not replace it to "b1".

Popeye
  • 11,839
  • 9
  • 58
  • 91
  • 1
    That will turn "bone" into "b1", am I right? Though maybe that is because of the way the OP phrased the question. – David Rönnqvist Dec 25 '13 at 18:21
  • Beat me to it. I was just typing out the same code. You may want to assert that the length of A2 is the same as A1 (or greater) or this could generate an invalid index error. – Joel Dec 25 '13 at 18:22
  • @Joel I have done it based on what they have asked and not included any validation checks in. But yes I would wrap this in some validation checks to make sure 1) length of each array is the same and 2) make sure the object returned at `objectAtIndex:` is an actual string. – Popeye Dec 25 '13 at 18:26