Dreamjar Dreamjar - 7 months ago 14
Swift Question

Get no. Of words in swift for average calculator

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

Answer
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 =  "".join(sentence.componentsSeparatedByCharactersInSet(NSCharacterSet.punctuationCharacterSet())).componentsSeparatedByString(" ").filter{$0 != ""}

println(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]"
println(wordList.count)  // 79

The question is to get the count of words but if you need the words as they are, you can use this extension adapted from the method suggested by Martin R in this answer do be able to deal with apostrophes also:

extension String {
    var words: [String] {
        var result:[String] = []
        enumerateSubstringsInRange(characters.indices, options: .ByWords) { result.append($0.substring!) }
        return result
    }
}

print(sentence.words.description) // ["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"]