在Objective-C中加入阵列


129

我正在寻找一种将NSMutableArray转换为字符串的方法。这个Ruby数组方法有什么可比的?

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

干杯!

Answers:


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

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


17

您正在寻找的方法是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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.