Matt
Matt

Reputation: 793

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

Is there any existing function that looks for the index of a substring inside another string? A method like .indexOfSubstring thank does this:

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

let indexOf: Int = word.indexOfSubstring("ere, how are")

println("index = " + \(indexOf))

and prints:

index = 6

Upvotes: 1

Views: 805

Answers (2)

Encore PTL
Encore PTL

Reputation: 8214

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

Upvotes: 1

Antonio
Antonio

Reputation: 72750

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

Upvotes: 2

Related Questions