Get the last character of a string without using array?
"Without using Array on swift"
Here you go:
var text = "Lorem ipsum"
var lastChar = text.substringFromIndex(text.endIndex.predecessor())
Swift 4:
First some char Last some char
let strOSName = "mac operating system"
print(strOSName.prefix(3)) //first char. o/p: MAC
print(strOSName.suffix(6)) //last char. o/p: system
let text = "Muhammad Raza"
println("\(text[advance(text.endIndex, -1)])")
in Short !
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 "ð"