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:

No comments:

Post a Comment