是否有快速方法为字符串数组中的每个元素添加字符串前缀?
答案 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"];