NSString replace repeated newlines with single newline

前端 未结 3 1329
孤独总比滥情好
孤独总比滥情好 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:41

    You can do it in the following way

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

    Hope it may help you..

    0 讨论(0)
  • 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"];
    
    0 讨论(0)
  • 2021-02-04 20:51

    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

    ?

    0 讨论(0)
提交回复
热议问题