OneBite.Dev - Coding blog in a bite size

Find The Last Occurrence Of A Character In A String In Swift

Code snippet for how to Find The Last Occurrence Of A Character In A String In Swift with sample and detail explanation

Searching for the last occurrence of a character in a string is a common operation in many programming scenarios. In the Swift programming language, this operation can be performed in a simple and efficient way. Here is a brief walk-through tutorial explaining how to find the last occurrence of a character in a string in Swift.

Code Snippet: Find The Last Occurrence Of A Character In A String In Swift

let text = "Hello, World!"
if let range = text.range(of: "o", options: .backwards) {
    let lastOccurrence = text.distance(from: text.startIndex, to: range.lowerBound)
    print(lastOccurrence)
}

Code Explanation for Find The Last Occurrence Of A Character In A String In Swift

In the above code, we are trying to find the last occurrence of character ‘o’ in the input string “Hello, World!“.

  1. First, we have a variable text which holds the string in which we want to find the last occurrence of a certain character.

  2. Next, we use the range(of:options:) method on the string text, passing two arguments. The first argument is “o”, which is the character we are looking for. The second argument is .backwards, which is a searching option that tells the method to start searching from the end of the string toward the beginning.

  3. This range(of:options:) method returns an optional Range<String.Index>. We use optional binding with if let to safely unwrap the range.

  4. If the character is found in the string, a Range object with the range of the last occurrence of the character is returned, which marks where the character starts and ends in the string.

  5. We then use the distance(from:to:) method on the string to calculate the index position of the last occurrence of the character in the string.

  6. The distance(from:to:)method takes two arguments - the start index of the string and the lowerBound of the range we got from step 3.

  7. Finally, we print the last occurrence index into the console.

In this way, we can easily find the index of the last occurrence of a character in a string in Swift.

swift