6

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!

2
  • 2
    What if they've renamed their device so it doesn't end with what you're expecting. My device name doesn't match the pattern you're looking for. Commented Oct 13, 2014 at 18:53
  • Please disclose why you want to access the user's name. Commented Nov 25, 2016 at 18:23

4 Answers 4

7

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) 
Sign up to request clarification or add additional context in comments.

Comments

7

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) 

Comments

2

In Swift3:

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

1 Comment

This code doesn't remove parenthesis... For ex: I want to replace this "\"(" by this "". But it doesn't work. It's like it doesn't recognize parentheses in strings. Any idea?
0

Swift 4 Code

//Add String extension

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

//Use string function like

let deviceName:String = "Mike's Iphone" let newName = deviceName.removeCharsFromEnd(count: "'s Iphone".length()) print(newName)// Mike 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.