Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove characters from a String in swift

Tags:

string

ios

swift

I am looking for a simple way to remove the 4 characters in the tilesColored String "ment" from the shuffledWord1.

var word1: String = "employment"
var shuffledWord1: String = "melpyoemtn"

var tilesColored: String = "ment"
var characters = Array(tilesColored) // gives ["m","e","n","t"]

let newWord1 = word1.StringByReplacingOccurencesOfString("\(characters[0])", withString:"") // gives "elpyoetn"

stringByReplacingOccurencesOfString only allows 1 character to be checked and removes BOTH m's, so how can I check against all 4 and only remove ONE instance of each to return "melpyo"?

Thanks in advance for any help possible

like image 820
richc Avatar asked Sep 01 '15 19:09

richc


People also ask

How do I remove a character from a string in Swift?

To remove the specific character from a string, we can use the built-in remove() method in Swift. The remove() method takes the character position as an argument and removed it from the string.

How do I remove the first 3 Characters of a string in Swift?

To remove the first character from a string , we can use the built-in removeFirst() method in Swift.

How do I remove the first character from a string in Swift 5?

Swift String dropFirst() The dropFirst() method removes the first character of the string.


1 Answers

Swift 3+ version with better performance than the previous top answers. (Because we don't separate into arrays with substrings, which all would need seperate allocations.)

This here just works on the unicode scalar level. You can paste it right into a playground.

import Foundation

extension String {

    func removeCharacters(from forbiddenChars: CharacterSet) -> String {
        let passed = self.unicodeScalars.filter { !forbiddenChars.contains($0) }
        return String(String.UnicodeScalarView(passed))
    }

    func removeCharacters(from: String) -> String {
        return removeCharacters(from: CharacterSet(charactersIn: from))
    }
}

let str = "n1o d2i3g4i5t6s!!!789"

let t1 = str.removeCharacters(from: CharacterSet.decimalDigits.inverted)
print(t1) // will print: 123456789

let t2 = str.removeCharacters(from: "0123456789")
print(t2) // will print: no digits!!!
like image 89
LimeRed Avatar answered Oct 18 '22 00:10

LimeRed