I have a string
let stringPlusString = TextBoxCal.text
I want to get the last character of stringPlusString
. I do not want to use array.
Java has charAt
but I could not find something similar in Swift
To get the last character of a string, call the charAt() method on the string, passing it the last index as a parameter. For example, str. charAt(str. length - 1) returns a new string containing the last character of the string.
Getting the last 3 characters To access the last 3 characters of a string, we can use the built-in Substring() method in C#. In the above example, we have passed s. Length-3 as an argument to the Substring() method.
Using last
to get the last Character
For Swift 4:
let str = "hello world😍" let lastChar = str.last! // lastChar is "😍"
For Swift 2 and Swift 3:
let str = "hello world😍" let lastChar = str.characters.last! // lastChar is "😍"
For Swift 1.2:
let str = "hello world😍" let lastChar = last(str)! // lastChar is "😍"
Subscripting the String
to get the last Character
This works for Swift 3 and Swift 4:
let str = "hello world😍" let lastChar = str[str.index(before: str.endIndex)] // lastChar is "😍"
And for Swift 1.2 and Swift 2:
let str = "hello world😍" let lastChar = str[str.endIndex.predecessor()] // lastChar is "😍"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With