Home
Map
String Find: range of ExampleUse range and contains to search for strings within other strings. Find a word in a string.
Swift
This page was last reviewed on Aug 18, 2023.
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.
Range
Next We test the result of range() for nil. If the optional exists, the variable "range" can be accessed directly.
Optional
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 18, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.