问题
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.
- Hello , @"" => Hello
- @"" , World => World
- 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