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

时间:2021-06-27 13:39:40

Is there a quick way to add a string prefix to each element in array of strings?

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

2 个解决方案

#1


6  

Define a category of NSMutableString

定义一个NSMutableString类别

@implementation NSMutableString (AppendPrefix)

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

@end

And then do:

然后做:

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

array here is an NSArray of NSMutableString

这里的数组是NSMutableString的NSArray

#2


1  

It's a bit longwinded, but this should work:

这有点冗长,但这应该是可行的:

- (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"];

#1


6  

Define a category of NSMutableString

定义一个NSMutableString类别

@implementation NSMutableString (AppendPrefix)

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

@end

And then do:

然后做:

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

array here is an NSArray of NSMutableString

这里的数组是NSMutableString的NSArray

#2


1  

It's a bit longwinded, but this should work:

这有点冗长,但这应该是可行的:

- (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"];