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."
Info Literal just means that characters are searched for as literals, with no transformations occurring in the search.
Here We specify a range within the input string to search. We use a full-string search.
Finally If our 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.
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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 18, 2023 (edit).