import Foundation
func groupByFirstNLetters(_ s: String, n: Int = 3) -> [String: [String]] {
let regex = try! NSRegularExpression(pattern: "[A-Za-z]+")
let lower = s.lowercased()
let range = NSRange(lower.startIndex..<lower.endIndex, in: lower)
var groups: [String: [String]] = [:]
for match in regex.matches(in: lower, range: range) {
if let r = Range(match.range, in: lower) {
let word = String(lower[r])
if word.count >= n {
let prefix = String(word.prefix(n))
groups[prefix, default: []].append(word)
}
}
}
return groups
}
let s = "The lowly inhabitants of the lowland were surprised to see the lower branches of the trees."
let groups = groupByFirstNLetters(s, n: 3)
// Print version 1
for (prefix, words) in groups {
print("\(prefix) :", words)
}
print()
// Print version 2
for (prefix, words) in groups {
print("\(prefix): \(words.joined(separator: ", "))")
}
/*
run:
inh : ["inhabitants"]
sur : ["surprised"]
low : ["lowly", "lowland", "lower"]
wer : ["were"]
tre : ["trees"]
bra : ["branches"]
the : ["the", "the", "the", "the"]
see : ["see"]
inh: inhabitants
sur: surprised
low: lowly, lowland, lower
wer: were
tre: trees
bra: branches
the: the, the, the, the
see: see
*/