如何在不使用swift数组的情况下获取字符串的最后一个字符?

时间:2014-08-04 07:28:22

标签: swift string

我有一个字符串

let stringPlusString = TextBoxCal.text

我想得到stringPlusString的最后一个字符我不想在java上使用数组charAt但我在swift上找不到这个关键字

6 个答案:

答案 0 :(得分:107)

使用last获取最后Character

Swift 4

let str = "hello world"
let lastChar = str.last!   // lastChar is ""

Swift 2 Swift 3

let str = "hello world"
let lastChar = str.characters.last!   // lastChar is ""

Swift 1.2

let str = "hello world"
let lastChar = last(str)!   // lastChar is ""

订阅String以获取最后Character

适用于 Swift 3 Swift 4

let str = "hello world"
let lastChar = str[str.index(before: str.endIndex)]   // lastChar is ""

Swift 1.2 Swift 2

let str = "hello world"
let lastChar = str[str.endIndex.predecessor()]   // lastChar is ""

答案 1 :(得分:6)

没有在swift上使用Array”

你走了:

var text = "Lorem ipsum"
var lastChar = text.substringFromIndex(text.endIndex.predecessor())

答案 2 :(得分:6)

斯威夫特4:

首先是一些char 最后一些char

let strOSName = "mac operating system"
print(strOSName.prefix(3))       //first char. o/p:  MAC
print(strOSName.suffix(6))       //last char.  o/p:  system

答案 3 :(得分:4)

    let text = "Muhammad Raza"
    println("\(text[advance(text.endIndex, -1)])")

简而言之!

答案 4 :(得分:1)

这是另一种从字符串中获取最后一个字母的简短方法:

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

方法last()返回一个可选的Character。

答案 5 :(得分:0)

详细信息

  • Swift 5.1,Xcode 11.2.1

解决方案

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))
    }
}

用法

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

完整样本

  

别忘了在此处粘贴解决方案代码

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))

日志

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: ""