130

I'm looking for a method of turning a NSMutableArray into a string. Is there anything on a par with this Ruby array method?

>> array1 = [1, 2, 3]
>> array1.join(',')
=> "1,2,3"

Cheers!

Sophie Alpert
  • 126,406
  • 35
  • 212
  • 233
Codebeef
  • 41,810
  • 20
  • 83
  • 116

3 Answers3

278
NSArray  *array1 = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];
NSString *joinedString = [array1 componentsJoinedByString:@","];

componentsJoinedByString: will join the components in the array by the specified string and return a string representation of the array.

ravron
  • 10,213
  • 2
  • 37
  • 62
Jason Coco
  • 76,627
  • 20
  • 180
  • 178
18

The method you are looking for is componentsJoinedByString.

NSArray  *a = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];//returns a pointer to NSArray
NSString *b = [a componentsJoinedByString:@","];//returns a pointer to NSString
NSLog(@"%@", b); // Will output 1,2,3
Rémy
  • 1,091
  • 8
  • 17
5

NSArray class reference:

NSArray *pathArray = [NSArray arrayWithObjects:@"here",
    @"be", @"dragons", nil];
NSLog(@"%@",
    [pathArray componentsJoinedByString:@" "]);
ravron
  • 10,213
  • 2
  • 37
  • 62
Georg Schölly
  • 116,521
  • 48
  • 204
  • 258