обновление: Xcode 8.2.1 • Swift 3.0.2
let sentence = "I want to an algorithm that could help find out how many words are there in a string separated by space or comma or some character. And then append each word separated by a character to an array which could be added up later I'm making an average calculator so I want the total count of data and then add up all the words. By words I mean the numbers separated by a character, preferably space Thanks in advance"
let wordList = sentence.components(separatedBy: .punctuationCharacters).joined().components(separatedBy: " ").filter{!$0.isEmpty}
print(wordList) // [I, want, to, an, algorithm, that, could, help, find, out, how, many, words, are, there, in, a, string, separated, by, space, or, comma, or, some, character, And, then, append, each, word, separated, by, a, character, to, an, array, which, could, be, added, up, later, Im, making, an, average, calculator, so, I, want, the, total, count, of, data, and, then, add, up, all, the, words, By, words, I, mean, the, numbers, separated, by, a, character, preferably, space, Thanks, in, advance]"
print(wordList.count) // 79
extension String {
var words: [String] {
var words: [String] = []
enumerateSubstrings(in: startIndex..<endIndex, options: .byWords) { word,_,_,_ in
guard let word = word else { return }
words.append(word)
}
return words
}
}
print(sentence.words) // ["I", "want", "to", "an", "algorithm", "that", "could", "help", "find", "out", "how", "many", "words", "are", "there", "in", "a", "string", "separated", "by", "space", "or", "comma", "or", "some", "character", "And", "then", "append", "each", "word", "separated", "by", "a", "character", "to", "an", "array", "which", "could", "be", "added", "up", "later", "I'm", "making", "an", "average", "calculator", "so", "I", "want", "the", "total", "count", "of", "data", "and", "then", "add", "up", "all", "the", "words", "By", "words", "I", "mean", "the", "numbers", "separated", "by", "a", "character", "preferably", "space", "Thanks", "in", "advance"]
Swift 2.x
let sentence = "I want to an algorithm that could help find out how many words are there in a string separated by space or comma or some character. And then append each word separated by a character to an array which could be added up later I'm making an average calculator so I want the total count of data and then add up all the words. By words I mean the numbers separated by a character, preferably space Thanks in advance"
let wordList = sentence.componentsSeparatedByCharactersInSet(NSCharacterSet.punctuationCharacterSet()).joinWithSeparator("").componentsSeparatedByString(" ").filter{$0 != ""}
print(wordList) // [I, want, to, an, algorithm, that, could, help, find, out, how, many, words, are, there, in, a, string, separated, by, space, or, comma, or, some, character, And, then, append, each, word, separated, by, a, character, to, an, array, which, could, be, added, up, later, Im, making, an, average, calculator, so, I, want, the, total, count, of, data, and, then, add, up, all, the, words, By, words, I, mean, the, numbers, separated, by, a, character, preferably, space, Thanks, in, advance]"
print(wordList.count) // 79
Вопрос заключается в том, чтобы получить количество слов, но если вам нужны слова, как они есть, вы можете использовать это расширение адаптированного метода, предложенное Мартин R в этом answer действительно быть в состоянии иметь дело с апострофа также:
extension String {
var words: [String] {
var result:[String] = []
enumerateSubstringsInRange(characters.indices, options: .ByWords) { result.append($0.substring!) }
return result
}
}
Это также удаляет апострофы, поэтому слово I is сводится к Im – Ian
+1 для решения 'enumerateSubstrings', потому что оно также работает с языками, которые не используют пространство часто, например ** японский или китайский **. справочная информация: https://medium.com/@sorenlind/three-ways-to-enumerate-the-words-in-a-string-using-swift-7da5504f0062 – Daniel