2016-10-19 8 views
0

隔離しようとしていますは、配列内の単語からの句読点を削除しません。Swiftの単語から句読点を分離する

は、例えば、この配列は、それらの中に句読点を持つ単語が含まれています

let words = ["hello", "world!!"] 

次のコードは、句読点のの分離を行います。

for i in 0..<words.count {   
    if let range = words[i].rangeOfCharacter(from: .punctuationCharacters) { 
     words.insert(words[i].substring(with: range), at: i+1) 
     words[i].replaceSubrange(range, with: "") 
    } 
} 

、結果としてwords配列は次のようになります。それは今ないよう

["hello", "world!", "!"] 

しかし、私は一度に代わり1で個別に句読点を分離する機能を希望:

["hello", "world", "!", "!"] 

現時点では、文字列の文字を繰り返して試してみましたが、CharacterSet.punctuationCharactersに対してテストしましたが、効率が悪く、clunky

私はこれをSwift-y方式でどのように達成できますか?

答えて

1

私はそれをやってのSwiftyファッション方法があるとは思いませんが、単語のあなたの配列が一致している場合は、次のように行うことができます。

let words = ["hello", "world!!"] 
var res: [String] = [] 
for word in words { 
    res += word.components(separatedBy: .punctuationCharacters).filter{!$0.isEmpty} 
    res += word.components(separatedBy: CharacterSet.punctuationCharacters.inverted).filter{!$0.isEmpty}.joined().characters.map{String($0)} 
} 
print(res) // ["hello", "world", "!", "!"] 
関連する問題