NSString replace repeated newlines with single newline

五迷三道 提交于 2019-12-03 10:14:38

问题


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.


回答1:


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



回答2:


For anyone looking for an Updated Swift 4 Answer:

extension String {

   func removeMultipleNewlinesFromMiddle() -> String {
       let returnString = trimmedString.replacingOccurrences(of: "\n+", with: "\n", options: .regularExpression, range: nil)
       return (returnString)
   }
}

Usage :

let str = "Hello \n\n\nWorld \n\nHow are you\n?"
print (str.removeMultipleNewlinesFromMiddle())

Output :

Hello

World

How are you

?




回答3:


You can do it in the following way

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

Hope it may help you..




回答4:


You can put this replacement inside a loop till you keep founding "\n\n" in your string.



来源:https://stackoverflow.com/questions/15876053/nsstring-replace-repeated-newlines-with-single-newline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!