2015-06-06 2 views
3

Я хочу сделать процедуру, чтобы узнать, сколько слов есть в строке, разделенной пробелом или запятой или другим символом. А затем добавьте общее количество позже.Количество слов в строке Swift для вычисления количества слов

Я делаю средний калькулятор, поэтому хочу получить общее количество данных, а затем добавить все слова.

ответ

10

обновление: 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 
    } 
} 
+1

Это также удаляет апострофы, поэтому слово I is сводится к Im – Ian

+1

+1 для решения 'enumerateSubstrings', потому что оно также работает с языками, которые не используют пространство часто, например ** японский или китайский **. справочная информация: https://medium.com/@sorenlind/three-ways-to-enumerate-the-words-in-a-string-using-swift-7da5504f0062 – Daniel

2

Вы можете попробовать componentsSeparatedByCharactersInset:

let s = "Let there be light" 

let c = NSCharacterSet(charactersInString: " ,.") 
let a = s.componentsSeparatedByCharactersInSet(c).filter({!$0.isEmpty}) 

// a = ["Let", "there", "be", "light"] 
+0

Спасибо! Это может сработать! И как добавить все числа в массив – Dreamjar

+1

Это не сработает в течение периода, за которым следует пробел. Это создало бы лишнюю пустую строку для каждого события –

+0

@LeoDabus - Хорошая точка, добавление фильтра, похоже, исправить. – MirekE

0

Вы можете попробовать следующие различные варианты:

let name = "some name with, space # inbetween" 
     let wordsSeparatedBySpaces = name.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) 
     let wordsSeparatedByPunctuations = name.componentsSeparatedByCharactersInSet(NSCharacterSet.punctuationCharacterSet()) 
     let wordsSeparatedByHashChar = name.componentsSeparatedByString("#") 
     let wordsSeparatedByComma = name.componentsSeparatedByString(",") 

     let total = wordsSeparatedBySpaces.count + wordsSeparatedByPunctuations.count + wordsSeparatedByHashChar.count + wordsSeparatedByComma.count 
     println("Total number of separators = \(total)") 
+0

Это не помогает! Добавление разделителей? 13 это * не * ответ, который он ищет ... – Grimxn

3
let sentences = "Let there be light!" 
let separated = split(sentences) { contains(",.! ", $0) }.count 

println(separated) // prints out 4 (if you just want the array, you can omit ".count") 

Если у вас есть определенное условие пунктуации, которое вы хотите использовать, вы можете использовать этот код. Также, если вы предпочитаете использовать только быстрые коды :).

+0

Хотя это может выглядеть лучше, производительность мудрая, это не так хорошо как сказал Лео. Хотя не имеет значения, если строки не астрономически длинны. – Eendje

Смежные вопросы