Find
, rangeA string
exists within another string
. We could use a complicated loop to find it. This is hard to write and maintain.
With range, we can locate a string
. A range is returned if the string
is found. If nothing is found, we receive an empty optional. We use an if-let
construct to test the result of range()
.
Our string
has the 4 words "a soft orange cat." It is a nice cat. We include Foundation at the top of the Swift file. We call range()
next and search for "orange."
string
search.range()
for nil
. If the optional exists, the variable "range" can be accessed directly.string
is found, we display the part after the first index, and the part before the string
.import Foundation // Input string. let line = "a soft orange cat" // Search for one string in another. var result = line.range(of: "orange", options: NSString.CompareOptions.literal, range: line.startIndex..<line.endIndex, locale: nil) // See if string was found. if let range = result { // Start of range of found string. let start = range.lowerBound // Display string starting at first index. print(line[start..<line.endIndex]) // Display string before first index. print(line[line.startIndex..<start]) }orange cat a soft
Contains
Here we invoke a method called "contains." We call this method on the string
"abc123abc." This returns true or false. If the argument exists in the string, it returns true.
import Foundation let value = "abc123abc" // See if the string contains the argument string. let result1 = value.contains("23a") print(result1) // This substring does not exist. let result2 = value.contains("def") print(result2)true false
With Swift, a specific method is often the easiest way of testing a string
. Here contains()
is often a good choice. For indexes, though, range()
with an "of" argument is effective.
In Swift we must address string
characters through ranges. To see where a string
exists in another, we must use ranges. And with optionals, we test for existence.