Convert NSArray to NSString in Objective-C

后端 未结 9 1212
难免孤独
难免孤独 2020-11-28 01:13

I am wondering how to convert an NSArray [@\"Apple\", @\"Pear \", 323, @\"Orange\"] to a string in Objective-C.

相关标签:
9条回答
  • 2020-11-28 01:32

    Objective C Solution

    NSArray * array = @[@"1", @"2", @"3"];
    NSString * stringFromArray = [[array valueForKey:@"description"] componentsJoinedByString:@"-"];   // "1-2-3"
    

    Those who are looking for a solution in Swift

    If the array contains strings, you can use the String's join method:

    var array = ["1", "2", "3"]
    
    let stringFromArray = "-".join(array) // "1-2-3"
    

    In Swift 2:

    var array = ["1", "2", "3"]
    
    let stringFromArray = array.joinWithSeparator("-") // "1-2-3"
    

    In Swift 3 & 4

    var array = ["1", "2", "3"]
    
    let stringFromArray = array.joined(separator: "-") // "1-2-3"
    
    0 讨论(0)
  • 2020-11-28 01:37

    I think Sanjay's answer was almost there but i used it this way

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

    Output :

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

    As Sanjay had hinted - I used method componentsJoinedByString from NSArray that does joining and gives you back NSString

    BTW NSString has reverse method componentsSeparatedByString that does the splitting and gives you NSArray back .

    0 讨论(0)
  • 2020-11-28 01:42

    I recently found a really good tutorial on Objective-C Strings:

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

    And I thought that this might be of interest:

    If you want to split the string into an array use a method called componentsSeparatedByString to achieve this:

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

    if you need to split on a set of several different characters, use NSString’s componentsSeparatedByCharactersInSet:

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

    Note however that the separator string can’t be blank. If you need to separate a string into its individual characters, just loop through the length of the string and convert each char into a new 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];
    }
    
    0 讨论(0)
提交回复
热议问题