如何在swift中删除String中的字符 [英] How to remove characters from a String in swift
问题描述
我正在寻找一种简单的方法来从shuffledWord1中删除tilesColored Stringment中的4个字符。
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只允许检查1个字符并删除BOTH m's,那么如何检查所有4个字符并且只删除每个4个实例以返回melpyo?
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版本的性能优于之前的最佳答案。 (因为我们没有将子串分成数组,所有这些都需要单独分配。)
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.)
这里只适用于unicode标量级别。您可以将其粘贴到游乐场。
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中删除String中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!