Search code examples
iosswiftstringtokenize

iOS String: remove prefix and suffix by CharacterSet


For a given String in Swift I need to remove prefix and suffix characters that belong to a predefined character set. I can use components(separatedBy:) with the character set and get rid of the empty strings at the beginning and end of the components array. Just wondering if there's a better approach?

Thanks!


Solution

  • You can use .trimmingCharacters(in: CharacterSet) on the string. From the 'help' text in Xcode on this function: "Returns a new string made by removing from both ends of the String characters contained in a given character set."

    Here is a unit test example using a custom character set. Notice it only removes characters from the start and end, not the middle (the comma stays):

    import XCTest
    class TrimCharacters: XCTestCase {
        func testExample() throws {
            let string = "abcbaHello, World!ccbbaa"
            let charactersToTrim = CharacterSet(charactersIn: "abc,")
            XCTAssertEqual(string.trimmingCharacters(in: charactersToTrim), "Hello, World!")
        }
    }
    

    There are also predefined character sets that can be useful. You can also invert a character set. See CharacterSet