How to get the index of the last instance of a character in a string with Swift

1 Answer

0 votes
import Foundation

let s = "Swift is a programming language for iOS, iPadOS, macOS"
let charToFind: Character = "O"

if let index = s.firstIndex(of: charToFind) {
    let position = s.distance(from: s.startIndex, to: index)
    print("The first occurrence of '\(charToFind)' is at index \(position)")
} else {
    print("'\(charToFind)' not found in the string")
}



/*
run:

The first occurrence of 'O' is at index 37

*/

 



answered Dec 29, 2024 by avibootz

Related questions

1 answer 1,099 views
1 answer 174 views
1 answer 228 views
1 answer 174 views
...