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 ?
Asked
Active
Viewed 127 times
-2
-
https://stackoverflow.com/questions/35285978/get-the-initials-from-a-name-and-limit-it-to-2-initials https://stackoverflow.com/questions/34540332/how-to-get-the-first-character-of-each-word-in-a-string – Larme May 04 '21 at 14:38
-
1[How to ask a good question](https://stackoverflow.com/help/how-to-ask) – Joakim Danielson May 04 '21 at 15:03
1 Answers
0
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()

aheze
- 24,434
- 8
- 68
- 125
-
1
-
-
1in the first approach you can get rid of the map when reducing your string `.reduce("") { $0 + $1.prefix(1) }` – Leo Dabus May 04 '21 at 14:52