Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the first six characters from a String (Swift)

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?

like image 758
Vandal Avatar asked Apr 13 '17 04:04

Vandal


People also ask

How do I remove the last two characters from a string Swift?

To remove the last character from a string we need to use the removeLast() method in swift.

How do I remove part of a string 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.

What is dropFirst in Swift?

Returns a subsequence containing all but the given number of initial elements.


2 Answers

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)

like image 123
Gefilte Fish Avatar answered Oct 08 '22 04:10

Gefilte Fish


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)) 
like image 20
Alain T. Avatar answered Oct 08 '22 02:10

Alain T.