我有一个函数:
func IphoneName() -> String
{
let device = UIDevice.currentDevice().name
return device
}
这段代码返回了iPhone的名称(简单)。我需要将末尾的"'s Iphone"
删除。我一直在阅读关于将其改为NSString并使用ranges的文章,但是我有些迷茫!
我有一个函数:
func IphoneName() -> String
{
let device = UIDevice.currentDevice().name
return device
}
这段代码返回了iPhone的名称(简单)。我需要将末尾的"'s Iphone"
删除。我一直在阅读关于将其改为NSString并使用ranges的文章,但是我有些迷茫!
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)
}
}
Test:
var deviceName:String = "Mike's Iphone"
let newName = deviceName.removeCharsFromEnd("'s Iphone".length()) // Mike
但如果您想使用“replace”方法,请使用stringByReplacingOccurrencesOfString
,如@Kirsteins
所发表的:
let newName2 = deviceName.stringByReplacingOccurrencesOfString(
"'s Iphone",
withString: "",
options: .allZeros, // or just nil
range: nil)
在这种情况下,您不必使用范围。您可以使用:
var device = UIDevice.currentDevice().name
device = device.stringByReplacingOccurrencesOfString("s Iphone", withString: "", options: .allZeros, range: nil)
在Swift3中:
var device = UIDevice.currentDevice().name
device = device.replacingOccurrencesOfString("s Iphone", withString: "")
Swift 4 代码
//添加字符串扩展
extension String {
func removeCharsFromEnd(count:Int) -> String{
let stringLength = self.count
let substringIndex = (stringLength < count) ? 0 : stringLength - count
let index: String.Index = self.index(self.startIndex, offsetBy: substringIndex)
return String(self[..<index])
}
func length() -> Int {
return self.count
}
}
//使用字符串函数,例如
let deviceName:String = "Mike's Iphone"
let newName = deviceName.removeCharsFromEnd(count: "'s Iphone".length())
print(newName)// Mike