Swift is there a method that gives the index of a substring inside another string

 ̄綄美尐妖づ 提交于 2019-12-01 14:40:27

You can use the rangeOfString method:

import Foundation

let word: String = "Hey there, how are you?"

if let range = word.rangeOfString("ere, how are") {
    let index = distance(word.startIndex, range.startIndex)
    println("index = \(index)")
}

It returns a range, i.e. both sides of the searched string - just use the startIndex property.

Note that this is a method borrowed from NSString

There is no build in method in Swift. You will need to implement it yourself. Another implementation of this is

/// Get the start index of string
///
/// :return start index of .None if not found
public func indexOf(str: String) -> Int? {
    return self.indexOfRegex(Regex.escapeStr(str))
}

/// Get the start index of regex pattern
///
/// :return start index of .None if not found
public func indexOfRegex(pattern: String) -> Int? {
    if let range = Regex(pattern).rangeOfFirstMatch(self).toRange() {
        return range.startIndex
    }
    return .None
}

This code is from this library which has bunch of extensions for common swift types such as String https://github.com/ankurp/Dollar.swift/blob/master/Cent/Cent/String.swift#L62

You can checkout the docs on the usage http://www.dollarswift.org/#indexof-str-string-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!