Objective-C 如何在一行上打印 NSSet(没有尾随逗号/空格) [英] Objective-C How to print NSSet on one line (no trailing comma / space)
本文介绍了Objective-C 如何在一行上打印 NSSet(没有尾随逗号/空格)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在一行中打印出一个 NSSet,逗号分隔但没有尾随逗号或空格.我该怎么做?
Im trying to print out an NSSet on a single line, comma separation but no trailing comma or space. how can i do this?
我知道这适用于数组:
NSMutableString *outputStringArray = [[NSMutableString alloc] init];
NSMutableArray *myArray = [[NSMutableArray alloc] initWithCapacity:10];
for (int k = 0; k < [myArray count]; k++) {
[outputStringArray appendFormat:@"%@, ", [myArray objectAtIndex:k]];
}
NSLog(@"%@", [outputStringArray substringToIndex:[outputStringArray length] - 2]);
但是由于集合没有索引,我不能这样做.
but since sets don't have indexing i cant do this.
谢谢
推荐答案
你总是可以从一个集合中创建一个数组,像这样:
You can always make an array out of a set, like this:
NSArray *myArray = [mySet allObjects];
之后,您可以使用 componentsJoinedByString:
:
NSString *str = [myArray componentsJoinedByString:@", "];
当然,您可以使用类似于您帖子中的循环的简单循环来实现相同的效果:
Of course you can achieve the same effect with a simple loop similar to the one in your post:
BOOL isFirst = YES;
for (id element in mySet) {
if (!isFirst) {
[outputStringArray appendString:@", "];
} else {
isFirst = NO;
}
[outputStringArray appendFormat:@"%@", element];
}
这篇关于Objective-C 如何在一行上打印 NSSet(没有尾随逗号/空格)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文