【问题标题】:Replace array of characters in NSString [closed]替换NSString中的字符数组[关闭]
【发布时间】:2013-12-25 17:02:01
【问题描述】:

我正在尝试替换 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 的相应成员。

【问题讨论】:

  • 你有没有看过 NSString 的规范???

标签: objective-c replace nsstring nsarray nscharacterset


【解决方案1】:

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"

如 cmets 中所述,此代码可以将“bone”返回为“b1”。为了解决这个问题,您可以将您的数组替换为:

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

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

【讨论】:

  • 这会将“bone”变成“b1”,对吗?虽然这可能是因为 OP 表达问题的方式。
  • 打败我。我只是在输入相同的代码。您可能想要断言 A2 的长度与 A1 相同(或更大),否则可能会产生无效索引错误。
  • @Joel 我是根据他们的要求完成的,并且没有包含任何验证检查。但是是的,我会将其包装在一些验证检查中以确保 1)每个数组的长度相同和 2) 确保在 objectAtIndex: 返回的对象是一个实际的字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
  • 1970-01-01
相关资源
最近更新 更多