我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。

下面是完整的例子:

var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)

Swift 4.0(也叫Swift 5.0)

var str = "Hello, World"                           // "Hello, World"
str.dropLast()                                     // "Hello, Worl" (non-modifying)
str                                                // "Hello, World"
String(str.dropLast())                             // "Hello, Worl"

str.remove(at: str.index(before: str.endIndex))    // "d"
str                                                // "Hello, Worl" (modifying)

斯威夫特3.0

api变得更加敏捷了,因此Foundation扩展也做了一些改变:

var name: String = "Dolphin"
var truncated = name.substring(to: name.index(before: name.endIndex))
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

或者就地版本:

var name: String = "Dolphin"
name.remove(at: name.index(before: name.endIndex))
print(name)      // "Dolphi"

谢谢Zmey, Rob Allen!

Swift 2.0+方式

有几种方法可以做到这一点:

通过Foundation扩展,尽管不是Swift库的一部分:

var name: String = "Dolphin"
var truncated = name.substringToIndex(name.endIndex.predecessor())
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

使用removeRange()方法(改变名称):

var name: String = "Dolphin"    
name.removeAtIndex(name.endIndex.predecessor())
print(name) // "Dolphi"

使用dropLast()函数:

var name: String = "Dolphin"
var truncated = String(name.characters.dropLast())
print(name)      // "Dolphin"
print(truncated) // "Dolphi"

旧的字符串。索引(Xcode 6 Beta 4 +)方式

由于Swift中的字符串类型旨在提供出色的UTF-8支持,您不能再使用Int类型访问字符索引/范围/子字符串。相反,您使用String。指数:

let name: String = "Dolphin"
let stringLength = count(name) // Since swift1.2 `countElements` became `count`
let substringIndex = stringLength - 1
name.substringToIndex(advance(name.startIndex, substringIndex)) // "Dolphi"

或者(对于一个更实用,但教育意义更小的例子),你可以使用endIndex:

let name: String = "Dolphin"
name.substringToIndex(name.endIndex.predecessor()) // "Dolphi"

注意:我发现这是理解String的一个很好的起点。指数

旧(pre-Beta 4)方式

你可以简单地使用substringToIndex()函数,提供它比String的长度小1:

let name: String = "Dolphin"
name.substringToIndex(countElements(name) - 1) // "Dolphi"

let str = "abc"
let substr = str.substringToIndex(str.endIndex.predecessor())  // "ab"

全局的dropLast()函数作用于序列,因此也作用于字符串:

var expression  = "45+22"
expression = dropLast(expression)  // "45+2"

// in Swift 2.0 (according to cromanelli's comment below)
expression = String(expression.characters.dropLast())

这是一个字符串扩展表单:

extension String {

    func removeCharsFromEnd(count_:Int) -> String {
        let stringLength = count(self)

        let substringIndex = (stringLength < count_) ? 0 : stringLength - count_

        return self.substringToIndex(advance(self.startIndex, substringIndex))
    }
}

对于Swift 1.2之前的版本:

...
let stringLength = countElements(self)
...

用法:

var str_1 = "Maxim"
println("output: \(str_1.removeCharsFromEnd(1))") // "Maxi"
println("output: \(str_1.removeCharsFromEnd(3))") // "Ma"
println("output: \(str_1.removeCharsFromEnd(8))") // ""

参考:

扩展向现有的类、结构或枚举类型添加新功能。这包括扩展您无法访问原始源代码的类型的能力(称为回溯建模)。扩展类似于Objective-C中的类别。(与Objective-C类别不同,Swift扩展没有名称。)

看文档


使用函数removeAtIndex(i: String.Index)

var s = "abc"    
s.removeAtIndex(s.endIndex.predecessor())  // "ab"

使用函数advance(startIndex, endIndex):

var str = "45+22"
str = str.substringToIndex(advance(str.startIndex, countElements(str) - 1))

var str = "Hello, playground"

extension String {
    var stringByDeletingLastCharacter: String {
        return dropLast(self)
    }
}

println(str.stringByDeletingLastCharacter)   // "Hello, playgroun"

简单回答(2015-04-16有效):removeAtIndex(mystring . endindex .前任())

例子:

var howToBeHappy = "Practice compassion, attention and gratitude. And smile!!"
howToBeHappy.removeAtIndex(howToBeHappy.endIndex.predecessor())
println(howToBeHappy)
// "Practice compassion, attention and gratitude. And smile!"

元:

语言继续着它的快速进化,使得许多以前很好的sos答案的半衰期变得危险地短暂。学习语言并参考真正的文档总是最好的。


一个快速变化的类别:

extension String {
    mutating func removeCharsFromEnd(removeCount:Int)
    {
        let stringLength = count(self)
        let substringIndex = max(0, stringLength - removeCount)
        self = self.substringToIndex(advance(self.startIndex, substringIndex))
    }
}

使用:

var myString = "abcd"
myString.removeCharsFromEnd(2)
println(myString) // "ab"

我建议使用NSString来处理你想要操作的字符串。实际上,作为一个开发人员,我从来没有遇到过NSString的问题,Swift String可以解决…我明白其中的微妙之处。但我还没有真正需要它们。

var foo = someSwiftString as NSString

or

var foo = "Foo" as NSString

or

var foo: NSString = "blah"

然后整个简单NSString字符串操作的世界就向你敞开了。

作为问题的答案

// check bounds before you do this, e.g. foo.length > 0
// Note shortFoo is of type NSString
var shortFoo = foo.substringToIndex(foo.length-1)

斯威夫特4:

let choppedString = String(theString.dropLast())

在Swift 2中,这样做:

let choppedString = String(theString.characters.dropLast())

我推荐这个链接来了解Swift字符串。


补充上述代码,我想删除字符串的开头,但在任何地方都找不到引用。以下是我的做法:

var mac = peripheral.identifier.description
let range = mac.startIndex..<mac.endIndex.advancedBy(-50)
mac.removeRange(range)  // trim 17 characters from the beginning
let txPower = peripheral.advertisements.txPower?.description

这将从字符串的开头修剪17个字符(字符串的总长度是67,从末尾向前移动-50,就得到了它。


修剪字符串最后一个字符最简单的方法是:

title = title[title.startIndex ..< title.endIndex.advancedBy(-1)]

另一种方法如果你想从末尾删除一个或多个字符。

var myStr = "Hello World!"
myStr = (myStr as NSString).substringToIndex((myStr as NSString).length-XX)

其中XX是要删除的字符数。


Swift 3(根据文档)2016年11月20日

let range = expression.index(expression.endIndex, offsetBy: -numberOfCharactersToRemove)..<expression.endIndex
expression.removeSubrange(range)

使用新的Substring类型用法:

斯威夫特4:

var before: String = "Hello world!"
var lastCharIndex: Int = before.endIndex
var after:String = String(before[..<lastCharIndex])
print(after) // Hello world

短:

var before: String = "Hello world!"
after = String(before[..<before.endIndex])
print(after) // Hello world

斯威夫特4

var welcome = "Hello World!"
welcome = String(welcome[..<welcome.index(before:welcome.endIndex)])

or

welcome.remove(at: welcome.index(before: welcome.endIndex))

or

welcome = String(welcome.dropLast())

函数的作用是:删除字符串的最后一个元素。

var expression = "45+22"
expression = expression.dropLast()

Swift 3:当你想删除尾随字符串:

func replaceSuffix(_ suffix: String, replacement: String) -> String {
    if hasSuffix(suffix) {
        let sufsize = suffix.count < count ? -suffix.count : 0
        let toIndex = index(endIndex, offsetBy: sufsize)
        return substring(to: toIndex) + replacement
    }
    else
    {
        return self
    }
}

斯威夫特4.2

我还删除了我的最后一个字符从字符串(即UILabel文本)在IOS应用程序

@IBOutlet weak var labelText: UILabel! // Do Connection with UILabel

@IBAction func whenXButtonPress(_ sender: UIButton) { // Do Connection With X Button

    labelText.text = String((labelText.text?.dropLast())!) // Delete the last caracter and assign it

}


斯威夫特4/5

var str = "bla"
str.removeLast() // returns "a"; str is now "bl"

import UIKit

var str1 = "Hello, playground"
str1.removeLast()
print(str1)

var str2 = "Hello, playground"
str2.removeLast(3)
print(str2)

var str3 = "Hello, playground"
str3.removeFirst(2)
print(str3)

Output:-
Hello, playgroun
Hello, playgro
llo, playground

我更喜欢下面的实现,因为我不必担心,即使字符串是空的

let str = "abc"
str.popLast()

// Prints ab

str = ""
str.popLast() // It returns the Character? which is an optional

// Print <emptystring>