-1

我正在尝试替换 NSString 中的字符数组。

例如,如果我们有这个字符串:

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

我需要用 A2 的相应成员替换在 A1 中找到的该字符串的所有成员。

4

1 回答 1

3

NSString有一个名为的实例方法,stringByReplacingOccurencesOfString:请参阅Apple Documentation for NSString以获取有关实际方法的帮助 - 代码方面,您可以尝试以下代码。

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"

如注释中所述,此代码可以将“bone”返回为“b1”。为了解决这个问题,我想你可以用以下方式替换你的数组:

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

请注意,我所做的一切都是在空格中添加的,因此如果您有“bone”,它不会将其替换为“b1”。

于 2013-12-25T18:19:49.383 回答