NSString replace repeated newlines with single newline

前端 未结 3 1332
孤独总比滥情好
孤独总比滥情好 2021-02-04 20:06

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 co

3条回答
  •  一向
    一向 (楼主)
    2021-02-04 20:50

    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"];
    

提交回复
热议问题