我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。
下面是完整的例子:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
我如何从字符串变量使用Swift删除最后一个字符?在文档中找不到。
下面是完整的例子:
var expression = "45+22"
expression = expression.substringToIndex(countElements(expression) - 1)
当前回答
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
其他回答
使用新的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
使用函数removeAtIndex(i: String.Index)
var s = "abc"
s.removeAtIndex(s.endIndex.predecessor()) // "ab"
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
另一种方法如果你想从末尾删除一个或多个字符。
var myStr = "Hello World!"
myStr = (myStr as NSString).substringToIndex((myStr as NSString).length-XX)
其中XX是要删除的字符数。
补充上述代码,我想删除字符串的开头,但在任何地方都找不到引用。以下是我的做法:
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,就得到了它。