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

时间:2014-10-08 10:08:57

标签: ios iphone swift string

我有一个功能:

func IphoneName() -> String
{
    let device = UIDevice.currentDevice().name
    return device
}

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

4 个答案:

答案 0 :(得分: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)
    }
}

测试:

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)

答案 1 :(得分:7)

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

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

答案 2 :(得分:2)

在Swift3中:

var device = UIDevice.currentDevice().name
device = device.replacingOccurrencesOfString("s Iphone", withString: "")

答案 3 :(得分:0)

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