1

Hi i have a nsmutable array full of keywords and i wish to key each object and spit it out with a comma after each object example below. The NSMutable array is called KeywordArray

Array Structure

Keyword 1
Keyword 2
Keyword 3
Keyword 4 
Keyword 5
Keyword 6 
Keyword 7

I wish to convert that NSMutableArray into the following format within a NSString

Keyword 1, Keyword 2, Keyword 3, Keyword 4, Keyword 5, Keyword 6, Keyword 7

Thanks

Mason

user393273
  • 1,430
  • 5
  • 25
  • 48

3 Answers3

5

You can use the componentsJoinedByString: method of NSArray to join the elements in the array using a separator. This will work with an NSMutableArray as well, because NSMutableArray inherits from NSArray.

NSMutableArray *array = ...;
NSString *string = [array componentsJoinedByString:@", "];

See the NSArray class reference for more information.

Greg
  • 33,450
  • 15
  • 93
  • 100
3

You can do it easily:

NSMutableArray *testArray = [[NSMutableArray alloc] initWithObjects:@"keyword1", @"keyword2" @"keyword3", nil];
NSString *string = [testArray componentsJoinedByString:@","];

Same case, but with NSArray was discussed here

Community
  • 1
  • 1
ppolak
  • 641
  • 5
  • 8
2

NSArray *arr;
[arr componentsJoinedByString:@", "];

unexpectedvalue
  • 6,079
  • 3
  • 38
  • 62
  • Doesn't matter, componentsJoinedByString: works for NSMutableArray and NSArray. Returns a NSString. – unexpectedvalue Mar 25 '11 at 15:09
  • 1
    It doesn't matter that it's a mutable array, because NSMutableArray is a subclass of NSArray. Therefore it has access to all methods that NSArray has. – GendoIkari Mar 25 '11 at 15:10