Search code examples
objective-cnsstringnsmutablestring

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)


Solution

  • 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.)