130

我正在寻找一种将 NSMutableArray 转换为字符串的方法。有什么可以与这个 Ruby 数组方法相提并论的吗?

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

干杯!

4

3 回答 3

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

componentsJoinedByString:将通过指定的字符串连接数组中的组件并返回数组的字符串表示形式。

于 2009-05-10T16:50:51.060 回答
18

您正在寻找的方法是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
于 2009-05-10T16:50:57.487 回答
5

NSArray类参考

NSArray *pathArray = [NSArray arrayWithObjects:@"here",
    @"be", @"dragons", nil];
NSLog(@"%@",
    [pathArray componentsJoinedByString:@" "]);
于 2009-05-10T16:51:46.580 回答