Winter Winter - 1 year ago 51
Objective-C Question

How to replace \n with comma and remove the last \n ? - iOS Objective C

I want to display text which return from server in a label. Server return something like this

*English\nMalay\nTamil\n*
.

Currently I use:

stringByReplacingOccurrencesOfString:@"\n" withString:@", "


to replace the
\n
with comma. But how do I remove the last
\n
?

Now my text in the label shows:


"English, Malay, Tamil,"


I would like to get like


"English, Malay, Tamil"

Answer Source

Try like this way.

NSString *string =  @"English\nMalay\nTamil\n";
//Make array from string
NSMutableArray *array = [NSMutableArray arrayWithArray:[string componentsSeparatedByString:@"\n"]];
//Remove all empty object from array
[array removeObject:@""];
//Join array object and make string
NSString *newString = [array componentsJoinedByString:@", "];
NSLog(@"%@",newString);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download