Removing characters from a string in Swift

17,923

Solution 1

What about this:

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

But if you want replace method use stringByReplacingOccurrencesOfString as @Kirsteins posted:

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

Solution 2

You don't have to work with ranges in this case. You can use:

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

Solution 3

In Swift3:

var device = UIDevice.currentDevice().name
device = device.replacingOccurrencesOfString("s Iphone", withString: "")
Share:
17,923
Jason
Author by

Jason

Updated on June 09, 2022

Comments

  • Jason
    Jason almost 2 years

    I have a function:

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

    Which returns the name of the iPhone (simple). I need to remove the "'s Iphone" from the end. I have been reading about changing it to NSString and use ranges, but I am a bit lost!