Index of a substring in a string with Swift

前端 未结 11 1646
自闭症患者
自闭症患者 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:56

    Doing this in Swift is possible but it takes more lines, here is a function indexOf() doing what is expected:

    func indexOf(source: String, substring: String) -> Int? {
        let maxIndex = source.characters.count - substring.characters.count
        for index in 0...maxIndex {
            let rangeSubstring = source.startIndex.advancedBy(index)..

    This function is not optimized but it does the job for short strings.

提交回复
热议问题