【问题标题】:How can I remove the last character of a String in Swift 4? [duplicate]如何在 Swift 4 中删除字符串的最后一个字符? [复制]
【发布时间】:2018-04-29 05:46:32
【问题描述】:

如何在 Swift 4 中删除字符串的最后一个字符?我曾经在早期版本的 Swift 中使用 substring,但不推荐使用 substring 方法。

这是我的代码。

temp = temp.substring(to: temp.index(before: temp.endIndex))

【问题讨论】:

    标签: swift string substring swift4


    【解决方案1】:

    dropLast() is your safest bet,因为它处理 nil 和空字符串而不会崩溃 (answer by OverD),但是如果你想返回你删除的字符,请使用 removeLast()

    var str = "String"
    let removedCharacter = str.removeLast() //str becomes "Strin"
                                            //and removedCharacter will be "g"
    

    一个不同的函数,removeLast(_:)改变了应该删除的字符数:

    var str = "String"
    str.removeLast(3) //Str
    

    两者的区别在于removeLast()返回被移除的字符,而removeLast(_:)没有返回值:

    var str = "String"
    print(str.removeLast()) //prints out "g"
    

    【讨论】:

    • removeLast() 移除并返回集合的最后一个元素。检查:developer.apple.com/documentation/swift/string/…
    • @MoeAbdul-Hameed 谢谢,我编辑了我的答案。
    • 这个答案应该发布到重复的问题而不是这个问题。
    • 注意如果字符串为空会崩溃
    • 我会推荐dropLast,它在应用于空String时返回一个空Substring,而不是崩溃。
    【解决方案2】:

    你可以使用dropLast()

    您可以在Apple documentation找到更多信息

    【讨论】:

    • 这是最安全的方法
    • nilempty"" 运行良好。
    【解决方案3】:

    代码的文字 Swift 4 转换是

    temp = String(temp[..<temp.index(before: temp.endIndex)])
    
    • foo.substring(from: index) 变为 foo[index...]

    • foo.substring(to: index) 变为 foo[..&lt;index]

      在特定情况下,必须从Substring 结果创建一个新的String

    但是the4kmen's answer中的解决方案要好得多。

    【讨论】:

    • 如果字符串为空也会崩溃
    • 确实如此,问题中的表达也是如此。
    猜你喜欢
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2011-11-18
    • 2011-08-01
    相关资源
    最近更新 更多