xcode 来自 NSArray 的 NSString

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14366431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 02:32:06  来源:igfitidea点击:

NSString from NSArray

iosobjective-cxcodensstringnsarray

提问by NNikN

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

我正在尝试从 Array 创建一个字符串。但是,如何生成它是有条件的,如下所述。

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. 你好,@"" => 你好
  2. @"" , 世界 => 世界
  3. 你好,世界 => 你好,世界

回答by Alladinian

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:@","]);

回答by dasblinkenlight

You cannot store nilvalues 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.

您不能将nil值存储在NSArray* 中,因此答案是否定的。您需要自己迭代数组,跟踪是否需要添加逗号。

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];
}



**nilnilNS 集合中的值用NSNullNSNull对象表示。