替换NSString中的字符数组

时间:2013-12-25 17:02:01

标签: objective-c replace nsstring nsarray nscharacterset

我正在尝试从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];

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

1 个答案:

答案 0 :(得分: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"

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

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

注意我所做的就是添加到空格中,所以如果你有“骨头”,它就不会将它替换为“b1”。