NSString replaces duplicate newline with one newline

I have NSStringone that can have several \ n between the lines. I need to replace multiple occurrence \ n with one \ n.

I tried this code:

newString = [string stringByReplacingOccurrencesOfString:@"\n\n" withString:@"\n"];

But this does not give the desired result if the string contains the series "\ n \ n \ n \ n \ n \ n". In this case, they will be replaced by "\ n \ n \ n".

What should I do to replace multiple "\ n" with one "\ n"?

Thanks everyone!

Update: adding a screenshot for UITextViewto which the filtered string is set as text. It seems that new lines look more than after writing code, as suggested by Attila H in response. enter image description here

+3
3

NSRegularExpression. :

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

NSArray *arrSplit = [s componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
                s = [arrSplit componentsJoinedByString:@"\n"];

, .

+1

You can put this replacement inside the loop until you save "\ n \ n" in your string.

-1
source

All Articles