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

下面是完整的例子:

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

当前回答

斯威夫特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())

其他回答

使用新的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:

let choppedString = String(theString.dropLast())

在Swift 2中,这样做:

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

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

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

let str = "abc"
str.popLast()

// Prints ab

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

// Print <emptystring>
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

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

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