I have quick question about Swift algorithm, assuming I have a string “New Message” which option I need to use to get just initials NM ?
1 Answer
I would use map to get the first character of each word in the string, then use reduce to combine them.
let string = "New Message" let individualWords = string.components(separatedBy: " ") let firstCharacters = individualWords.map { $0.prefix(1) }.reduce("", +) print("firstCharacters is \(firstCharacters)") Result:
firstCharacters is NM
Edit: Per @LeoDabus' comment, joined is more concise than reduce("", +), and does the same thing.
let firstCharacters = individualWords.map { $0.prefix(1) }.joined()