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”?

  • How Can I Get A List of Available System Sounds in iOS?
  • How To Properly Add Child View Controller in iOS 8 With Swift
  • Can't get Location in iOS (GEOErrorDomain Code=-204)
  • GMT to Local Time Conversion with Daylight Saving Time change
  • string parsing to double fails in C++
  • In Cocoa KVO, why doesn't a change on a NSMutableArray proxy notify observers?
  • Thanks in advance for any help possible

    5 Solutions Collect From Internet About “How to remove characters from a String in swift”

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

    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: "")
        }
    }
    

    So you want to replace each character only once, starting from the right hand side? Try this (Swift 2.0):

    var word1: String = "employment"
    var shuffledWord1: String = "melpyoemtn"
    
    var tilesColored: String = "ment"
    var searchOption : NSStringCompareOptions = .BackwardsSearch
    
    for c in tilesColored.characters {
        if let range = shuffledWord1.rangeOfString(String(c), options: searchOption) {
            shuffledWord1 = shuffledWord1.stringByReplacingCharactersInRange(range, withString: "")
        }
    }
    
    print(shuffledWord1) // melpyo
    

    Remove the .characters if you are using Swift 1.2