Swift如何从短语中获取具有多个字符的字典

时间:2016-04-26 23:15:35

标签: arrays string swift dictionary

我想用一个字符串创建一个字典,其中包含单词和每个单词的字符数。

var textToShow:String = "Try not to become a man of success, but" //rather try to become a man of value. Albert Einstein"

    print(charactersCount(textToShow))

func charactersCount(s: String) -> Dictionary<String, Int> {
    var words = s.componentsSeparatedByString(" ")
    var characterInWordDictionary = Dictionary<String, Int>()

    for word in words {
            characterInWordDictionary[word] = word.characters.count
    }
    return characterInWordDictionary
}

问题是,使用这种方法,它会返回

 ["Try": 3, "not": 3, "a": 1, "become": 6, "of": 2, "but": 3, "man": 3, "to": 2, "success,": 8]

不是那么糟糕,但是: - 首先,字典的顺序不正确 - 第二,我也想在字典中的空间。

我想要回归的是:

["Try": 3, " ": 1, "not": 3, " ": 1, "to": 2, " ": 1, "become": 6, " ": 1, "a": 1, " ": 1, "man": 3, " ": 1, "of": 2, " ": 1, "success,": 8, " ": 1, "but": 3]

如果有人可以就此提供任何指导,那就太棒了。

韩国社交协会,

2 个答案:

答案 0 :(得分:1)

我为你写了一个小功能:

var textToShow:String = "Try not to become a man of success, but" // rather try to become a man of value. Albert Einstein"



func charactersCount(s: String) -> [(String, Int)] {
    var result = [(String, Int)]()

    var word = String(s[s.startIndex.advancedBy(0)])
    var size = 1

    var space = s[s.startIndex.advancedBy(0)] == " "

    for (var i:Int = 1; i < s.characters.count; i++) {
        if (s[s.startIndex.advancedBy(i)] == " ") {
            if (space) {
                size++
                word.append(s[s.startIndex.advancedBy(i)])
            } else {
                result.append((word, size))
                size = 1
                space = true
                word = " "
            }
        } else {
            if (space) {
                result.append((word, size))
                size = 1
                space = false
                word = String(s[s.startIndex.advancedBy(i)])
            } else {
                size++
                word.append(s[s.startIndex.advancedBy(i)])
            }
        }
    }
    result.append((word, size))

    return result
}

print(charactersCount(textToShow))

输出结果为:

["Try": 3, " ": 1, "not": 3, " ": 1, "to": 2, " ": 1, "become": 6, " ": 1, "a": 1, " ": 1, "man": 3, " ": 1, "of": 2, " ": 1, "success,": 8, " ": 1, "but": 3]

答案 1 :(得分:1)

首先创建一个空的tupleArray。接下来使用componentsSeparatedByString分解你的句子并使用forEach迭代所有元素(单词)以附加该元素($ 0 =单词)及其字符数,然后是(&#34;&#34;,1)的元组。然后使用popLast删除那个额外的元组。试试这样:

let textToShow = "Try not to become a man of success, but"

var tupleArray:[(String, Int)] = []

textToShow.componentsSeparatedByString(" ")
          .forEach{tupleArray += [($0,$0.characters.count),(" ",1)]}
tupleArray.popLast()
print(tupleArray.description)  // "[("Try", 3), (" ", 1), ("not", 3), (" ", 1), ("to", 2), (" ", 1), ("become", 6), (" ", 1), ("a", 1), (" ", 1), ("man", 3), (" ", 1), ("of", 2), (" ", 1), ("success,", 8), (" ", 1), ("but", 3)]\n"