我有一个函数:
func IphoneName() -> String
{
let device = UIDevice.currentDevice().name
return device
}
返回 iPhone 的名称(简单)。我需要从最后删除 "'s Iphone"
。我一直在阅读有关将其更改为 NSString 并使用范围的信息,但我有点迷路了!
最佳答案
这个怎么样:
extension String {
func removeCharsFromEnd(count:Int) -> String{
let stringLength = countElements(self)
let substringIndex = (stringLength < count) ? 0 : stringLength - count
return self.substringToIndex(advance(self.startIndex, substringIndex))
}
func length() -> Int {
return countElements(self)
}
}
测试:
var deviceName:String = "Mike's Iphone"
let newName = deviceName.removeCharsFromEnd("'s Iphone".length()) // Mike
但是,如果您想要替换方法,请使用 stringByReplacingOccurrencesOfString
作为 @Kirsteins
发布:
let newName2 = deviceName.stringByReplacingOccurrencesOfString(
"'s Iphone",
withString: "",
options: .allZeros, // or just nil
range: nil)
关于ios - 从 Swift 中的字符串中删除字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26254309/