OneBite.Dev - Coding blog in a bite size

Find The Index Of A Substring Within A String In Swift

Code snippet for how to Find The Index Of A Substring Within A String In Swift with sample and detail explanation

Working with strings is a common task in programming and Swift is no different. In this article, we’ll explore how you can find the index of a substring within a string in Swift.

Code snippet: Finding the index of a substring within a string

To accomplish this task, Swift provides a method called range(of:). Here’s how you can use it:

let mainString = "Hello, Swift Programming!"
let subString = "Swift"

if let range = mainString.range(of: subString) {
    let index = mainString.distance(from: mainString.startIndex, to: range.lowerBound)
    print("The index of substring is: \(index)")
}

In this code, mainString is the string we are searching in and subString is the string we are searching for.

Code Explanation for Finding the index of a substring within a string

The first thing we need to do is to get the range of the subString in the mainString. The range(of:) method is used for this purpose. It returns an optional range indicating the start and end indices of subString within mainString. If subString is not found in mainString, it returns nil.

if let range = mainString.range(of: subString)

This line of code makes use of optional binding to safely unwrap the optional range. If subString is found within mainString, the range is unwrapped and assigned to the range constant.

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

The distance(from:to:) method is used to calculate the index of the start of the subString in the mainString. The distance is calculated from the start index of the mainString to the lower bound of the range.

print("The index of substring is: \(index)")

Finally, we print the index to the console. This will provide us with the position where the subString starts in the mainString.

That’s all there is to it! With Swift’s built-in string methods, finding the index of a substring is a straightforward process. It’s another proof of Swift’s power and flexibility when it comes to handling strings.

swift