55

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

Eugene Berdnikov
  • 2,150
  • 2
  • 23
  • 30
Gökhan Çokkeçeci
  • 1,388
  • 3
  • 16
  • 37
  • 1
    Swift isn't Java, that's why. Look at [this awesome blog post](http://oleb.net/blog/2014/07/swift-strings/). – dasdom Aug 04 '14 at 07:33
  • Ofc i know swift isn't java i just give a example if java exist like this method %100 swift exist too . – Gökhan Çokkeçeci Aug 04 '14 at 07:45
  • Possible duplicate of [Get nth character of a string in Swift programming language](http://stackoverflow.com/questions/24092884/get-nth-character-of-a-string-in-swift-programming-language) – Martin R Aug 04 '14 at 07:47
  • yes this method possible but i think, %100 must be exist any method for get a last character am i wrong ? java exist , c# exist, swift should be exist ? – Gökhan Çokkeçeci Aug 04 '14 at 08:15
  • 2
    @MartinR I think this is a special case: there's a more efficient way to get the last character of a string from the endIndex than to get the nth character in general. Some of the solutions to that question will be awful for this case, as they iterate from the beginning of the string. – Matt Gibson Aug 04 '14 at 10:53
  • @MattGibson: I thought that it can be derived easily from the answers given there, but you might be right. Closing vote retracted. – Martin R Aug 04 '14 at 11:05
  • 2
    @MattGibson: But I am not completely sure if `advance(text.endIndex, -1)` really performs better. With the new support for extended grapheme clusters (e.g. "flags") it *might* be necessary to iterate from the start of the string anyway to determine the last character correctly. – Martin R Aug 04 '14 at 11:40
  • Yup, that's a fair point. Though I'd hope in the end that at least endIndex might be cached on first use and only reset if the String changed. If I had time I'd do some benchmarking right now... – Matt Gibson Aug 04 '14 at 12:42
  • @vacawama: The [swift3] and [swift4] tags are for *"questions **directly related to changes** in version 3/4 of Apple's Swift programming language"*. I don't think that these tags should be added to a question if an answer has been updated for newer Swift versions. – Martin R Jun 06 '17 at 07:02

6 Answers6

138

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 ""
vacawama
  • 150,663
  • 30
  • 266
  • 294
15

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
Deepak Tagadiya
  • 2,187
  • 15
  • 28
6

"Without using Array on swift"

Here you go:

var text = "Lorem ipsum"
var lastChar = text.substringFromIndex(text.endIndex.predecessor())
Oscar Swanros
  • 19,767
  • 5
  • 32
  • 48
4
    let text = "Muhammad Raza"
    println("\(text[advance(text.endIndex, -1)])")

in Short !

Muhammad Raza
  • 952
  • 7
  • 24
3

Details

  • Swift 5.1, Xcode 11.2.1

Solution

extension String {
    func onlyLastCharacters(_ count: Int) -> String { return String(suffix(count)) }
    func onlyLastCharacters(_ count: Int, checkLength: Bool) -> String? {
        if checkLength {
            if self.count >= count { return onlyLastCharacters(count) }
            return nil
        }
        return String(suffix(count))
    }
}

Usage

str.onlyLastCharacters(6)
str.onlyLastCharacters(13, checkLength: true)

Full sample

Do not forget to paste here the solution code

var testNumber = 0
func show(original: String, modified: String?) {
    testNumber += 1
    if let string = modified {
        print("\(testNumber). Original: \"\(original)\", modified: \"\(string)\"")
    } else {
        print("\(testNumber). nil | count: nil")
    }
}

var str = "Hello world!"
show(original: str, modified: str.onlyLastCharacters(6))
show(original: str, modified: str.onlyLastCharacters(12))
show(original: str, modified: str.onlyLastCharacters(13, checkLength: false))
show(original: str, modified: str.onlyLastCharacters(13, checkLength: true))

str = ""
show(original: str, modified: str.onlyLastCharacters(10))
show(original: str, modified: str.onlyLastCharacters(10, checkLength: true))
show(original: str, modified: str.onlyLastCharacters(10, checkLength: false))

Log

1. Original: "Hello world!", modified: "world!"
2. Original: "Hello world!", modified: "Hello world!"
3. Original: "Hello world!", modified: "Hello world!"
4. nil | count: nil
5. Original: "", modified: ""
6. nil | count: nil
7. Original: "", modified: ""
Vasily Bodnarchuk
  • 24,482
  • 9
  • 132
  • 127
1

Here is another shorter way to get the last letter from string:

let text = "some string"
last(text) // returns {Some "a"}

The method last() returns an optional Character.

Anvar Azizov
  • 545
  • 1
  • 6
  • 9