aryaxt
aryaxt

Reputation: 77596

Objective-C - Replace all double new lines with 1 new line?

I have an html string, and I want to allow 1 linebreak at a time. I am trying to replacing all "\n\n" with "\n". But at the end I end up with double line-breaks.

Is it possible to print the content of a string to see what the content is, so instead of going to a new line display "\n" in the output window.

while ((range = [html rangeOfString:@"\n\n"]).length) 
{
   [html replaceCharactersInRange:range withString:@"\n"];
}

EDIT: html has been converted to plain text (so there are no BR tags in the string)

Upvotes: 1

Views: 1153

Answers (2)

Chuck
Chuck

Reputation: 237010

If you have an indeterminate number of newlines that you want to compress into one, you can use NSRegularExpression. Something like:

NSRegularExpression *squeezeNewlines = [NSRegularExpression regularExpressionWithPattern:@"\n+" options:0 error:nil];
[squeezeNewlines replaceMatchesInString:html options:0 range:NSMakeRange(0, [html length]) withTemplate:@"\n"];

(Written in my browser and not tested since I don't have a recent Mac on hand, so let me know if I messed anything up.)

Upvotes: 4

onnoweb
onnoweb

Reputation: 3038

Why don't you use instead:

- (NSUInteger)replaceOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)opts range:(NSRange)searchRange

Upvotes: 1

Related Questions