Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the initials from a name and limit it to 2 initials

Tags:

ios

swift

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?

like image 270
Nico Avatar asked Feb 09 '16 07:02

Nico


People also ask

How do you write initials with name example?

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.

How can I get initials from a given name?

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 ().

How to find initials from a name in Python?

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.

How to extract initials from a list of names in Excel?

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 happens when you enter a string with a single name?

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.


1 Answers

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)
}
like image 67
Cherpak Evgeny Avatar answered Oct 05 '22 23:10

Cherpak Evgeny