NSString from NSArray

梦想与她 提交于 2019-12-07 06:02:59

问题


I am trying to create a String from Array.But, there is condition to how it should be generated, as explained below.

NSArray *array=[NSArray arrayWithObjects:@"Hello",@"World",nil];
[array componentsJoinedByString:@","];

This will output: Hello,World.

But, if first Item is Empty,then is there way to receive the only second one.

  1. Hello , @"" => Hello
  2. @"" , World => World
  3. Hello , World => Hello,World

回答1:


Another way to do this is to grab a mutable copy of the array and just remove non valid objects. Something like this perhaps:

NSMutableArray *array = [[NSArray arrayWithObjects:@"",@"World",nil] mutableCopy];
[array removeObject:@""]; // Remove empty strings
[array removeObject:[NSNull null]]; // Or nulls maybe

NSLog(@"%@", [array componentsJoinedByString:@","]);



回答2:


You cannot store nil values in NSArray*, so the answer is "no". You need to iterate the array yourself, keeping track of whether you need to add a comma or not.

NSMutableString *res = [NSMutableString string];
BOOL first = YES;
for(id item in array) {
    if (id == [NSNull null]) continue;
    // You can optionally check for item to be an empty string here
    if (!first) {
        [res appendString:@", "];
    } else {
        first = NO;
    }
    [res appendFormat:@"%@", item];
}


*nil values in NS collections are represented with NSNull objects.

来源:https://stackoverflow.com/questions/14366431/nsstring-from-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!