如何在swift中删除String中的字符

时间:2015-09-01 19:43:46

标签: ios string swift

我正在寻找一种简单的方法来删除tilesColored String"中的4个字符"来自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只允许检查1个字符并删除两个字符,所以如何检查所有4个字符,并且只删除每个字符的一个实例以返回" melpyo"?

提前感谢您提供任何可能的帮助

5 个答案:

答案 0 :(得分:15)

Swift 3版本,性能优于之前的顶级答案。 (因为我们不会将子串分成数组,所有这些都需要单独分配。)

这里只适用于unicode标量级别。你可以将它粘贴到游乐场。

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

答案 1 :(得分:4)

Macondo2Seattle的Swift 3版本的答案,我认为这是最优雅的解决方案。

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

答案 2 :(得分:1)

extension String
{
    func removeCharacters(characters: String) -> String
    {
        let characterSet = NSCharacterSet(charactersInString: characters)
        let components = self.componentsSeparatedByCharactersInSet(characterSet)
        let result = components.joinWithSeparator("")
        return result
    }
}

答案 3 :(得分:0)

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"

答案 4 :(得分:0)

迅速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."