我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。
下面是完整的例子:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。
下面是完整的例子:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
当前回答
let str = "abc"
let substr = str.substringToIndex(str.endIndex.predecessor()) // "ab"
其他回答
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
}
}
补充上述代码,我想删除字符串的开头,但在任何地方都找不到引用。以下是我的做法:
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,就得到了它。
let str = "abc"
let substr = str.substringToIndex(str.endIndex.predecessor()) // "ab"
函数的作用是:删除字符串的最后一个元素。
var expression = "45+22"
expression = expression.dropLast()
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