代码之家  ›  专栏  ›  技术社区  ›  stevenpcurtis

计算字符串中出现的字母

  •  0
  • stevenpcurtis  · 技术社区  · 6 年前

    找到了一种计算字符串中字符出现次数的可爱方法:

    let inputString = "test this string"
    var frequencies : [Character: Int] = [:]
    
    let baseCounts = zip(
        inputString, repeatElement(1,count: Int.max))
    frequencies = Dictionary(baseCounts, uniquingKeysWith: +)
    

    结果呢

    [“i”:2,“r”:1,“n”:1,“e”:1,“s”:3,“:2,“g”:1,“t”:4,“h”:1]

    但是我试着用一个范围来表示元素

    let secondBaseCounts = zip(inputString, 0...)
    frequencies = Dictionary(secondBaseCounts, uniquingKeysWith: +)
    

    但得到的结果不正确:

    [“i”:20,“r”:12,“n”:14,“e”:1,“s”:20,“:13,“g”:15,“t”:19,“h”:6]

    为什么?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Dávid Pásztor    6 年前

    你的第二次尝试没有实现你想要实现的。 zip(inputString, 0...) Int 每个字符到字符本身的索引。

    secondBaseCounts

    打电话 Dictionary(secondBaseCounts, uniquingKeysWith: +) 对与重复键关联的每个值求和,这意味着 frequencies 字典将是所有索引的总和,其中某个字符出现在字典中 inputString 而不是那个角色出现的次数。

        2
  •  0
  •   Shrikant Phadke    4 年前

    var inputString = "test this string"
    
    extension String {
        
        func countCharacterOccurances() -> Dictionary<String, Any> {
            var occuranceDict : [String : Int] = [:]
           
            for i in self {
                var count = 1
                if occuranceDict[String(i)] == nil  {
                    occuranceDict[String(i)] = count
                }
                else {
                    count = occuranceDict[String(i)] ?? 0
                    count += 1
                    occuranceDict[String(i)] = count
                }
            }
            return occuranceDict as Dictionary<String, Any>
        }
    }
    var characterOccuranceDict = inputString.countCharacterOccurances()
    

    输出:[“h”:1,“t”:4,“i”:2,“g”:1,“s”:3,“r”:1“,”:2,“n”:1,“e”:1]

    let sortedDictionary = characterOccuranceDict.sorted { $0.key < $1.key }
    sortedDictionary.forEach { (item) in 
        finalStr = finalStr + item.key + String(describing: item.value)
    }
    print(finalStr)
    

    输出:A3B2C4D1