I have a the following name: John Fitzgerald Kennedy
.
To get its initials, I created a method:
extension String {
public var first: String {
return String(self[startIndex])
}
}
let initials = "John Fitzgerald Kennedy".componentsSeparatedByString(" ")
.reduce("") { $0 + $1.first }
The output is : JFK
Is there an elegant way with my method (with reduce) to limit those initials to JK
only, removing then the letter in the middle?
Initials are the capital letters which begin each word of a name. For example, if your full name is Michael Dennis Stocks, your initials will be M. D. S.
Often when you are processing customer records or doing mail merge, it might be useful to get initials from a given name, like JFK for John F Kennedy. You can do this using simple text formulas (left (), mid (), find ()) combined with if ().
You can do this using simple text formulas (left (), mid (), find ()) combined with if (). Here is how: As you can see, I have used different logic to find initials, based on the number of spaces in the name.
There are several methods can extract each initials from a list of names in Excel, here in this tutorial, it provides a formula to handle this job. Name: the full names you want to extract the initials. This formula only extract initials from first three words, start from the forth word, it will ignore.
WHAT HAPPENED: The function splits the incoming string, ignores any name between the first & last names and returns their initials. In the case a single name is entered, a single initial is returned. I hope this helps, cheers.
If you target iOS 9 and above:
let formatter = PersonNameComponentsFormatter()
if let components = formatter.personNameComponents(from: name) {
formatter.style = .abbreviated
return formatter.string(from: components)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With