5

I'm working with the Twitter API which provides only a single field called name, which includes the full name of a person.

The application that we're constructing requires a first name and a last name.

Now my question is how I am able to extract the first and last name from a single name field.

I know that I can simply just split or explode the string but this won't work if the person for example has first name which consists of more than one word.

  • 6
    Related reading: kalzumeus.com/2010/06/17/… – Biffen Nov 17 '14 at 11:13
  • @biffen I'd go so far as to state required reading before implementing anything that treats personal names as anything other than blobs. – Jules Nov 17 '14 at 16:15
10

There are lots of simple ways of doing this wrong - read this to see why. There is no way of getting it right programmatically.

That said, some of the wrong ways are not that bad, all things considered. If you can live with making occasional errors and correcting them with a list of exceptions after users notify you, then naive splitting on white space might be the right thing to do. But you must exercise your judgement whether that's the right trade-off for your application.

  • I disagree about the ways it can go wrong not being bad. There are huge variations in how people structure their names. For any realistic purpose for which you might want to split a personal name into forename and surname, the potential to cause offense to large numbers of people is huge. Leaving aside the simple problem of people with names structured like "A B C" (is B part of the given name or family name? both are common in different places) there are entire cultures where people place their surname first, either always (e.g. Japan) or only in formal circumstances (e.g. France). – Jules Nov 17 '14 at 20:49
  • I wish this post ranked higher in Google than the hundreds of "How to split First and Last names in Excel" articles - as if they will be remotely accurate. *facepalm* – Simon East Mar 5 '18 at 21:26
-2

I would consider using a regular expression pattern with grouping to extract only the beginning and the end words.

  • this reads more like a comment, see How to Answer – gnat Nov 17 '14 at 20:31
  • 2
    Writing the code is easy. Deciding on which rules to use is the hard part. – CodesInChaos Nov 18 '14 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.