Reputation: 1624
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?
Upvotes: 0
Views: 76
Reputation: 236360
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"
Upvotes: 1
Reputation: 1319
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
Upvotes: 1
Reputation: 1319
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
Upvotes: 1
Reputation: 4513
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.
Upvotes: 3