Home > Blockchain >  Remove consecutive whitespaces and all newlines in String
Remove consecutive whitespaces and all newlines in String

Time:10-25

I have a screen in which I show message previews of users. The previews should not contain newlines and consecutive whitespaces, exactly like the message previews in WhatsApp.

I currently have this code:

// String extension
public func prepareForInOverviewOrPushNotification() -> String {
    replacingOccurrences(of: "\n", with: " ")
            .replacingOccurrences(of: " {2,}", with: " ", options: .regularExpression)
}

This works, but I am calling this code in a hot loop and I want to improve the performance. The .regularExpression isn't cached and 2 replaces take place. I looked into the compiled Regex and NSRegularExpression, but with Regex I don't see a 'replace' option and with NSRegularExpression I need to convert my String to an NSString which doesn't help performance either.

This is a test which should remain working:

import MyProject
import XCTest

class StringOverviewTest: XCTestCase {
    func test() {
        check(input: "hi", expected: "hi")
        // Double whitespace
        check(input: "hi  X", expected: "hi X")
        check(input: """
                     hi 


                     weird long text

                     1
                     """, expected: "hi weird long text 1")
    }

    func check(
        input: String,
        expected: String
    ) {
        XCTAssertEqual(input.prepareForInOverviewOrPushNotification(), expected)
    }
}

CodePudding user response:

You can use [ \n] (one or more spaces or newlines) instead of replacing newlines with space and then shrinking two or more spaces with a single space:

public func prepareForInOverviewOrPushNotification() -> String {
    replacingOccurrences(of: "[\n ] ", with: " ")
}

Or, just use \s :

public func prepareForInOverviewOrPushNotification() -> String {
    replacingOccurrences(of: #"\s "#, with: " ")
}
  • Related