Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last character of a string without using array?

Tags:

string

swift

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

like image 376
Gökhan Çokkeçeci Avatar asked Aug 04 '14 07:08

Gökhan Çokkeçeci


People also ask

How do I get the last character of a string?

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.

How do I get the last 3 characters of a 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.


1 Answers

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 "😍" 
like image 91
vacawama Avatar answered Oct 22 '22 10:10

vacawama