Index of a substring in a string with Swift

前端 未结 11 1695
自闭症患者
自闭症患者 2020-11-22 14:24

I\'m used to do this in JavaScript:

var domains = \"abcde\".substring(0, \"abcde\".indexOf(\"cd\")) // Returns \"ab\"

Swift doesn\'t have t

11条回答
  •  梦谈多话
    2020-11-22 14:58

    Swift 5

        extension String {
        enum SearchDirection {
            case first, last
        }
        func characterIndex(of character: Character, direction: String.SearchDirection) -> Int? {
            let fn = direction == .first ? firstIndex : lastIndex
            if let stringIndex: String.Index = fn(character) {
                let index: Int = distance(from: startIndex, to: stringIndex)
                return index
            }  else {
                return nil
            }
        }
    }
    

    tests:

     func testFirstIndex() {
            let res = ".".characterIndex(of: ".", direction: .first)
            XCTAssert(res == 0)
        }
        func testFirstIndex1() {
            let res = "12345678900.".characterIndex(of: "0", direction: .first)
            XCTAssert(res == 9)
        }
        func testFirstIndex2() {
            let res = ".".characterIndex(of: ".", direction: .last)
            XCTAssert(res == 0)
        }
        func testFirstIndex3() {
            let res = "12345678900.".characterIndex(of: "0", direction: .last)
            XCTAssert(res == 10)
        }
    

提交回复
热议问题