From:
let fruit = ["012Red Apple", "03218Yellow Banana", "11 Orange Orange"] I would like to get:
var result = ["Red Apple", "Yellow Banana", "Orange Orange"] What is the best way to do this in the latest Swift?
You can do it like this
var fruitAlpha: [String] = [] for f in fruit { fruitAlpha.append(f.stringByTrimmingCharactersInSet(NSCharacterSet.letterCharacterSet().invertedSet)) } As Leo noted, it's better to use just letter set and just invert it. This will work for all non letter characters.
stringByTrimmingCharactersInSet is not a good choice. It trims away characters in the specified set from the beginning AND end of the string, until the first occurrence of a character not in the specified set. So "012Red Apple8675309" would get trimmed to "Red Apple".You can use a regular expression like this:
let fruits = ["012Apple", "03218Banana", "11 Orange"] var results = [String]() for fruit in fruits { if let match = fruit.rangeOfString("[a-zA-Z]+", options: .RegularExpressionSearch) { results.append(fruit.substringWithRange(match)) } } print(results) // Apple, Banana, Orange Try this regex, i think it'll fit what you want:
let fruits = ["012Apple red", "03218Banana cool", "11 Orange black 133"] var results = [String]() for fruit in fruits { if let match = fruit.rangeOfString("[a-zA-Z ]+", options: .RegularExpressionSearch) { results.append(fruit.substringWithRange(match)) } } print(results) // Apple red, Banana cool, Orange black You can also use a regex of find the range of digits, spaces, etc.. at the beginning of your strings and use removeRange() method:
var fruits = ["012Red Apple", "03218Yellow Banana", "11 Orange Orange"] for (index,fruit) in fruits.enumerate() { if let range = fruit.rangeOfString("[\\d )-]*\\s*", options: .RegularExpressionSearch) { fruits[index].removeRange(range) } } print(fruits) // ["Red Apple", "Yellow Banana", "Orange Orange"]\n"