OneBite.Dev - Coding blog in a bite size

Find The Position Of The First Occurrence Of A Substring In A String In Swift

Code snippet for how to Find The Position Of The First Occurrence Of A Substring In A String In Swift with sample and detail explanation

Working with strings can sometimes be challenging, and one such situation is when you need to find the position of the first occurrence of a substring in a string. This article teaches you how to get the first index of a substring in a string using Swift programming language.

Code snippet to find the position of the first occurrence of a substring in a string in Swift

let mainString = "Hello, World!"
let substring = "llo"

if let range = mainString.range(of: substring) {
    let position = mainString.distance(from: mainString.startIndex, to: range.lowerBound)
    print("The position of the first occurrence of \(substring) in \(mainString) is \(position)")
} else {
    print("\(substring) not found in \(mainString)")
}

Code Explanation for finding the position of the first occurrence of a substring in a string in Swift

Firstly, we define our main string and the substring that we are looking for.

let mainString = "Hello, World!"
let substring = "llo"

Next, we use the range(of:) function to find if the substring exists in the main string. This function returns an optional Range<String.Index> value representing the range of the substring in the main string if it exists.

if let range = mainString.range(of: substring) {
    ...
}

If the substring exists (i.e., range(of:) returns a non-nil value), we go ahead to calculate the position of the start of the range from the start of the main string.

let position = mainString.distance(from: mainString.startIndex, to: range.lowerBound)

The distance(from:to:) function returns the number of steps between two indices. Here, we are calculating the number of steps from the start of the main string to the start of the found range.

Finally, we print the value of the position.

print("The position of the first occurrence of \(substring) in \(mainString) is \(position)")

If the substring is not found (i.e., range(of:) returns nil), we print a corresponding message.

else {
    print("\(substring) not found in \(mainString)")
}

By following these steps, we can efficiently find the position of the first occurrence of a substring in a string in Swift.

swift