如何编写一个接受字符串输入并打印该字符串中最重复的第一个字符的方法

时间:2018-11-28 23:47:53

标签: arrays swift dictionary swift3

我试图创建一个可以迭代任何字符串并返回该字符串中最常见字符的函数。我的进度如下所示。我试图将字符数组插入字典中,然后可以打印出包含每个字符及其数量的字典。对于那些认为不费吹灰之力的人,我只是省略了所有我尝试过并注释掉的代码。没看到有什么用,所以只包含必需品。

let str = "sunday, monday, happy days"

var charStr = Array(str.characters)
var charDict = Dictionary<Character,Int>()
print("This is the character string array: " , charStr)

2 个答案:

答案 0 :(得分:2)

您可以轻松地遍历字符并增加字典中出现它的次数:

快捷键3

let str = "sunday, monday, happy days"
var charDict: [Character: Int] = [:]
for char in str.characters { 
    charDict[char] = (charDict[char] ?? 0) + 1
}
print(charDict)  //  ["d": 3, "u": 1, "a": 4, "h": 1, ",": 2, "n": 2, " ": 3, "m": 1, "o": 1, "y": 4, "s": 2, "p": 2]

您可以在字符集上使用max方法来获取字典的最大值

if let mostFrequent = charDict.max(by: { $0.value < $1.value }) {
    let chars = charDict.filter { $0.value == mostFrequent.value }
                        .map { $0.key }
                        .sorted()
    print("The most frequent characters are:", chars)   // ["a", "y"]
    print("Number of occurences:", mostFrequent.value) // 4
}

  

最常见的字符是:a

     

发生次数:4

答案 1 :(得分:-1)

let str = "sunday, monday, happy days"

let dict = str.reduce(into: [:]) { counts, word in counts[word, default: 0] += 1 }

print(dict)