Number of occurrences of substring in string in Swift

后端 未结 11 960
夕颜
夕颜 2020-12-02 19:37

My main string is \"hello Swift Swift and Swift\" and substring is Swift. I need to get the number of times the substring \"Swift\" occurs in the mentioned string.

T

11条回答
  •  庸人自扰
    2020-12-02 20:17

    Solution which uses a higher order functions

    func subStringCount(str: String, substr: String) -> Int {
        { $0.isEmpty ? 0 : $0.count - 1 } ( str.components(separatedBy: substr))
    }
    

    Unit Tests

    import XCTest
    
        class HigherOrderFunctions: XCTestCase {
    
            func testSubstringWhichIsPresentInString() {
                XCTAssertEqual(subStringCount(str: "hello Swift Swift and Swift", substr: "Swift"), 3)
            }
    
            func testSubstringWhichIsNotPresentInString() {
                XCTAssertEqual(subStringCount(str: "hello", substr: "Swift"), 0)
            }
    
        }
    

提交回复
热议问题