NSString replace repeated newlines with single newline

ios, iphone, nsstring, objective-c

Solution

You might use NSRegularExpression. This is the most simple and elegant way:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\n+" options:0 error:NULL];
NSString *newString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@"\n"];

Problem

I have an `NSString` which can have multiple \n in between the string. I need to replace the multiple occurrence of \n's with a single \n. I tried this code: ``` newString = [string stringByReplacingOccurrencesOfString:@"\n\n" withString:@"\n"]; ``` But this does not give the desired result if a series of "\n\n\n\n\n\n" is encountered in the string. In this case, they will be replaced with "\n\n\n". What should I do so that all more than one "\n"s be replaced with single "\n"? Thanks to all! Update: Adding a screenshot for `UITextView` to which the filtered string is set as text. The new lines seem to be more than one after writing code as suggested by Attila H in answer.

Original source