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

6

我有一个函数:

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

这段代码返回了iPhone的名称(简单)。我需要将末尾的"'s Iphone"删除。我一直在阅读关于将其改为NSString并使用ranges的文章,但是我有些迷茫!


2
如果他们已经将设备重命名,以便不以您期望的方式结尾,该怎么办?我的设备名称与您正在寻找的模式不匹配。 - Abizern
请透露您为什么要访问用户的姓名。 - Nikolai Ruhe
4个回答

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)
    }
}

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)

7

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

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

2

在Swift3中:

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

这段代码没有删除括号...例如:我想用""替换这个"("。但它不起作用。就像它不能识别字符串中的括号一样。有什么想法吗? - Paul Bénéteau

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接