Remove the first six characters from a String (Swift)
Solution 1
length
is the number of characters you want to remove (6 in your case)
extension String {
func toLengthOf(length:Int) -> String {
if length <= 0 {
return self
} else if let to = self.index(self.startIndex, offsetBy: length, limitedBy: self.endIndex) {
return self.substring(from: to)
} else {
return ""
}
}
}
Solution 2
In Swift 4 it is really simple, just use dropFirst(n: Int)
let myString = "Hello World"
myString.dropFirst(6)
//World
In your case: website.dropFirst(6)
Solution 3
Why not :
let stripped = String(website.characters.dropFirst(6))
Seems more concise and straightforward to me.
(it won't work with multi-char emojis either mind you)
[EDIT] Swift 4 made this even shorter:
let stripped = String(website.dropFirst(6))
Vandal
Updated on November 08, 2020Comments
-
Vandal over 3 years
What's the best way to go about removing the first six characters of a string? Through Stack Overflow, I've found a couple of ways that were supposed to be solutions but I noticed an error with them. For instance,
extension String { func removing(charactersOf string: String) -> String { let characterSet = CharacterSet(charactersIn: string) let components = self.components(separatedBy: characterSet) return components.joined(separator: "") }
If I type in a website like
https://www.example.com
, and store it as a variable named website, then type in the followingwebsite.removing(charactersOf: "https://")
it removes the
https://
portion but it also removes all h's, all t's, :'s, etc. from the text.How can I just delete the first characters?