简体   繁体   中英

How to remove characters from a String in 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

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!!!

Swift 3 version of Macondo2Seattle's answer, which, I think, is the most elegant solution.

extension String {
    func removing(charactersOf string: String) -> String {
        let characterSet = CharacterSet(charactersIn: string)
        let components = self.components(separatedBy: characterSet)
        return components.joined(separator: "")
    }
}

Swift 5:

var phrase = "The rain in Spain stays mainly in the plain."

let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
phrase.removeAll(where: { vowels.contains($0) })
// phrase == "Th rn n Spn stys mnly n th pln."
extension String {
    func removeCharacters(characters: String) -> String {
        let characterSet = NSCharacterSet(charactersInString: characters)
        let components = self.componentsSeparatedByCharactersInSet(characterSet)
        let result = components.joinWithSeparator("")
        return result
    }
}

Swift 2.0:

extension String {
  func stringByRemovingOnce(chars: String) -> String {
    var cs = Set(chars.characters)
    let fd = characters.filter { c in
      cs.remove(c).map { _ in false } ?? true
    }
    return String(fd)
  }
}

"melpyoemtn".stringByRemovingOnce("ment") // "lpyoem"

Swift 1.2:

extension String {
  func stringByRemovingOnce(chars: String) -> String {
    var cs = Set(chars)
    let fd = filter(self) { c in
      cs.remove(c).map { _ in false } ?? true
    }
    return String(fd)
  }
}

"melpyoemtn".stringByRemovingOnce("ment") // "lpyoem"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM