简体   繁体   中英

How to remove a new line from an NSArray output

I'm trying to remove the new line return from an NSArray output. I first converted it to a NSString to remove the () but the new line still shows up

NSString *myArrayString = [self.selectedStates description];

NSCharacterSet *charsToTrim = [NSCharacterSet characterSetWithCharactersInString:@"()\n\""];
myArrayString = [myArrayString stringByTrimmingCharactersInSet:charsToTrim];

the output I have looks like the following. I need to remove the new lines from somehow, so instead of this:

   1,
2,
3,
4,
5,
6

I would have 1,2,4,5,6

Relying on description is not a good idea . How about doing it the right way?

NSString *desc = [theArray componentsJoinedByString:@","];

(You can do it the way you approached it, by the way:

NSString *desc = [[theArray description] stringByReplacingOccurrencesOfString:@"\n" withString:@""];

but again, don't do this, please.)

Use - (NSString *)componentsJoinedByString:(NSString *)separator method of NSArray

Eg

NSArray *pathArray = [NSArray arrayWithObjects:@"here", @"be", @"dragons", nil];
NSLog(@"%@",[pathArray componentsJoinedByString:@","]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM