Monday, October 19, 2015

componentsSeparatedByCharactersInSet and join - Remove specific characters in a string

In this example, parenthesis "()" and white space " " are removed. For Xcode 6.4 (Swift 1.2):

let phoneOld = "(03)123 456 789" as NSString
let charSet = NSCharacterSet(charactersInString: "() ")

//Separate phoneOld by unwanted characters in charSet and form an array.
let phoneArray = phoneOld.componentsSeparatedByCharactersInSet(charSet) as! [String]


//Join all elements of phoneArray together without inserting any character between the elements.
let phoneNew = join("", phoneArray)


Results:



For Swift 2:

let phoneOld = "(03)123 456 789" as NSString
let charSet = NSCharacterSet(charactersInString: "() ")
let phoneArray = phoneOld.componentsSeparatedByCharactersInSet(charSet)

let phoneNew = phoneArray.joinWithSeparator("")

Related string function:

1 comment:

  1. Hi, for Swift 2.3, how can you execute this if you have multiple characters that needs to be replaced?

    Would you also know how to parse JSON strings in Swift 2.3? TIA

    ReplyDelete