0

I was trying to make a function that can iterate through any string and return the most common character within that string. My progress is shown below. I was trying to insert the character array into a dictionary where I could then print out the dictionary containing every character and their count. For the people that Think no effort was put in, I merely left out all of the code that I have tried and commented out. Didn't see any use for that so only the essentials were included.

let str = "sunday, monday, happy days"

var charStr = Array(str.characters)
var charDict = Dictionary<Character,Int>()
print("This is the character string array: " , charStr)
Paulw11
  • 108,386
  • 14
  • 159
  • 186

1 Answers1

2

You can easily iterate through your characters and increase the number of occurrences of it in your dictionary:

Swift 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]

You can use max method on your character collection to get the maximum value of your dictionary

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
}

The most frequent character is: a

Number of occurences: 4

Community
  • 1
  • 1
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571