How to get the last occurrence of a character in a string in Swift
In this tutorial, will see how to get the last occurrence of a character in a string in Swift. This task can be done easily with the help of in-built functions from Swift.
Step 1: Declare a variable of string type and define its value.
Step 2: Find the last index of occurrence of a character in the string using the lastIndex() method. It also includes spaces in counting.
lastIndex(of: element)
is an in-built method from Swift. It traverses through the string and returns the last index where the element is found. Or returns nil otherwise.- element: It is the parameter of a function. Which defines an element to search for in a string
Step 3: Print the index of the character if it is present in the string otherwise print character does not found.
utf16Offset(in: element)
is the method used to get the UTF-16 offset of the index from element.- element: It is a parameter that defines the element to search within for the index
Swift Code: last occurrence of a character in a string in Swift
var str = "Hello World" //string variable if let i = str.lastIndex(of: "l") //get last index of 'l' in str { print("The last occurrence of a character 'l' in 'Hello World' is at index : ", i.utf16Offset(in: str)) //print index i from string str } else { print("Character 't' is not present in 'Hello World'") }
Output :
The last occurrence of a character 'l' in 'Hello World' is at index : 9
Also, refer to Replace characters of a string in Swift
Leave a Reply