Replace array of characters in NSString

926 views Asked by At

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.

1

There are 1 answers

3
Popeye On BEST ANSWER

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".