在Objective-C中将NSArray转换为NSString

我想知道如何将NSArray [@"Apple", @"Pear ", 323, @"Orange"]转换为Objective-C中的string。

 NSString * result = [[array valueForKey:@"description"] componentsJoinedByString:@""]; 

一种方法是迭代数组,在每个项目上调用description消息:

 NSMutableString * result = [[NSMutableString alloc] init]; for (NSObject * obj in array) { [result appendString:[obj description]]; } NSLog(@"The concatenated string is %@", result); 

另一种方法是根据每个项目的类别做一些事情:

 NSMutableString * result = [[NSMutableString alloc] init]; for (NSObject * obj in array) { if ([obj isKindOfClass:[NSNumber class]]) { // append something } else { [result appendString:[obj description]]; } } NSLog(@"The concatenated string is %@", result); 

如果你想要逗号和其他无关的信息,你可以做:

 NSString * result = [array description]; 

我认为桑杰的回答几乎在那里,但我用这种方式

 NSArray *myArray = [[NSArray alloc] initWithObjects:@"Hello",@"World", nil]; NSString *greeting = [myArray componentsJoinedByString:@" "]; NSLog(@"%@",greeting); 

输出:

 2015-01-25 08:47:14.830 StringTest[11639:394302] Hello World 

正如Sanjay暗示的那样 – 我使用了NSArray中的方法componentsJoinedByString来join并返回NSString

顺便说一句, NSString具有反向方法componentsSeparatedByString做分裂,并让你NSArray回来。

我最近发现了一个关于Objective-Cstring的非常好的教程:

http://ios-blog.co.uk/tutorials/objective-c-strings-a-guide-for-beginners/

我认为这可能是有趣的:

如果要将string拆分为数组,请使用名为componentsSeparatedByString的方法来实现此目的:

 NSString *yourString = @"This is a test string"; NSArray *yourWords = [myString componentsSeparatedByString:@" "]; // yourWords is now: [@"This", @"is", @"a", @"test", @"string"] 

如果你需要分割一组不同的字符,使用NSString的componentsSeparatedByCharactersInSet:

 NSString *yourString = @"Foo-bar/iOS-Blog"; NSArray *yourWords = [myString componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"-/"] ]; // yourWords is now: [@"Foo", @"bar", @"iOS", @"Blog"] 

但请注意,分隔符string不能为空。 如果您需要将string分隔成单个字符,只需循环string的长度并将每个字符转换为新的string即可:

 NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]]; for (int i=0; i < [myString length]; i++) { NSString *ichar = [NSString stringWithFormat:@"%c", [myString characterAtIndex:i]]; [characters addObject:ichar]; } 
 NSString * str = [componentsJoinedByString:@""]; 

而你有DIC或多个arrays,然后用波纹pipe

 NSString * result = [[array valueForKey:@"description"] componentsJoinedByString:@""]; 
 NSArray *array = [NSArray arrayWithObjects:@"One",@"Second",@"Third", nil]; NSString *stringFromArray = [array componentsJoinedByString:@" "]; 

我知道的方式很简单。

 var NSArray_variable = NSArray_Object[n] var stringVarible = NSArray_variable as String 

n是SWIFT语言中数组的内部位置。 它可能在目标C中工作

Swift 3.0解决scheme:

 let string = array.joined(separator: ",")