Format array items for string output
I'm trying to display the items in an array us开发者_运维百科ing the following:
NSString *alertString = [NSString stringWithFormat:@"%@", path];
Which works fine, but when I display the string it gets displayed in the following way:
(
A, B, C, D )Is there a way to get it to display in a different way, such as all on one line and without brackets, commas or line returns like this:
A B C D
You have a few options. It looks like the objects within the array have a description
method that prints them the way you want to, so it may be as simple as using:
NSString *alertString = [path componentsJoinedByString:@" "];
If not, you could consider something like this:
NSMutableString *s = [NSMutableString string];
[path enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[s appendString:@" "];
[s appendString:[obj someMethodThatFormatsTheObject]];
}];
NSString *alertString = [NSString stringWithString:s];
Or even:
NSMutableArray *a = [NSMutableArray array];
[path enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[a addObject:[obj sometMethodThatFormatsTheObject]];
}];
NSString *alertString = [a componentsJoinedByString:@" "];
If that path
is an NSArray, you could use the -componentsJoinedByString:
method to concatenate all strings in the array with the desired separator.
NSString* alertString = [path componentsJoinedByString:@" "];
精彩评论