Swift - Data Type String Find

Introduction

To find a range within the string:

Demo

let swiftString:String = "The quick brown fox jumps over the lazy dog."

//creates a Range<Int> instance; start index at 4 and end at 8
let r = Range(start: 4, end: 8)

//create a String.Index instance to point to the starting char
let startIndex = advance(swiftString.startIndex, r.startIndex)

//create a String.Index instance to point to the end char
let endIndex = advance(startIndex, r.endIndex - r.startIndex + 1)

//create a Range<String.Index> instance
var range = Range (start: startIndex, end: endIndex)

//extract the substring using the Range<String.Index> instance
print(swiftString.substringWithRange(range))  //quick

Here, the substringWithRange() method extracts the characters starting from index 4 and ending at index 8.

The substringWithRange() method takes in a Range<String.Index> instance.

To find the position of a character within a string, you can use the find() method:

Demo

let swiftString:String = "The quick brown fox jumps over the lazy dog."

//finding the position of a character in a string
let char:Character = "i"
if let charIndex = find(swiftString, char) {
    let charPosition = distance(swiftString.startIndex, charIndex)
    print(charPosition)  //6
}

The find() method returns a String.Index instance.

In order to translate that into an integer, you need to use the distance() method.

Related Topic