C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
RangeIf let: We test the result of range() for nil. If the optional exists, the variable "range" can be accessed directly.
OptionalFinally: 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])
}
Output
orange cat
a soft
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)
Output
true
false