从Swift中的字符串中删除字符

Jas*_*son 5 string iphone ios swift

我有一个功能:

func IphoneName() -> String
{
    let device = UIDevice.currentDevice().name
    return device
}
Run Code Online (Sandbox Code Playgroud)

它返回iPhone的名称(简单).我需要"'s Iphone"从最后删除.我一直在阅读将其更改为NSString并使用范围,但我有点迷失!

Max*_*tin 7

那这个呢:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

测试:

var deviceName:String = "Mike's Iphone"

let newName = deviceName.removeCharsFromEnd("'s Iphone".length()) // Mike
Run Code Online (Sandbox Code Playgroud)

但是如果你想更换方法使用stringByReplacingOccurrencesOfString@Kirsteins发布:

let newName2 = deviceName.stringByReplacingOccurrencesOfString(
     "'s Iphone", 
     withString: "", 
     options: .allZeros, // or just nil
     range: nil)
Run Code Online (Sandbox Code Playgroud)


Kir*_*ins 7

在这种情况下,您不必使用范围.您可以使用:

var device = UIDevice.currentDevice().name
device = device.stringByReplacingOccurrencesOfString("s Iphone", withString: "", options: .allZeros, range: nil)
Run Code Online (Sandbox Code Playgroud)