0

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?

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

11 Comments

this would trim it also from the end of the string
@t1. you can use letterCharacterSet invertedSet
@LeoDabus totally missed that there were spaces in the requirements as well. In that case, inverted set is probably the best idea.
Trim is still not the best solution, it cuts off the end also, which is not acceptable here.
If your string can ever end in digits then 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".
|
1

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 

Comments

1

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 

Comments

1

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" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.