为字符串数组的每个元素添加前缀

时间:2011-05-05 21:09:17

标签: objective-c

是否有快速方法为字符串数组中的每个元素添加字符串前缀?

2 个答案:

答案 0 :(得分:6)

定义NSMutableString

的类别
@implementation NSMutableString (AppendPrefix)

- (void)appendPrefix:(NSString *)prefix {
    [self insertString:prefix atIndex:0];
}

@end

然后做:

[array makeObjectsPerformSelector:@selector(appendPrefix:) withObject:@"some_prefix"];

array这里是NSArray的{​​{1}}

答案 1 :(得分:1)

它有点长,但这应该有效:

- (NSArray *) prependArrayOfStrings:(NSArray*)originalArray prefix:(NSString*)prefix
{
  NSMutableArray *newArray = [[[NSMutableArray alloc] init] autorelease];
  for( NSString *currString in originalArray )
  {
    NSString *newString = [NSString stringwithFormat:@"%@%@", prefix, currString];
    [newArray addObject:newString];
  }

  return newArray;
}

// Somewhere else.
NSArray *originalArray = @[/*...*/];
// Fill in original array with array of strings
NSArray *newArray = [self prependArrayOfStrings:originalArray prefix:@"prefix"];