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 following
website.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?
To remove the last character from a string we need to use the removeLast() method in swift.
In the Swift string, we check the removal of a character from the string. To do this task we use the remove() function. This function is used to remove a character from the string. It will return a character that was removed from the given string.
Returns a subsequence containing all but the given number of initial elements.
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)
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With