Removing characters from a string in Swift

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 " Iphone" from the end. I read about changing it to NSString and using ranges, but I got a little confused!

+5
source share
4 answers

How 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 Iphone" let newName = deviceName.removeCharsFromEnd(" Iphone".length()) // Mike 

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

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

In this case, you do not need to work with ranges. You can use:

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

In Swift3:

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

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 the string function as

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

Source: https://habr.com/ru/post/1204244/


All Articles