Swift Find Strings: range of ExampleUse range and contains to search for strings within other strings. Find a word in a string.
dot net perls

Find, range. A 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().

An example. 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."

LiteralSearch This just means that characters are searched for as literals, with no transformations occurring in the search.

Range We specify a range within the input string to search. We use a full-string search.


If let We test the result of range() for nil. If the optional exists, the variable "range" can be accessed directly.


Finally If our string is found, we display the part after the first index, and the part before the string.

Swift program that uses range to search 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. var 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.

Swift program that uses contains
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.

Some notes. 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.

© 2007-2021 sam allen. send bug reports to info@dotnetperls.com.