-2

Hello I am trying to get the first and last name of a person. In my table I have a field that receives a person's full name like so

   João Afonso de Santos Silva

but I need to retrieve the

  first name João and then his last name Silva

and then combine thoes two strings. The end result should look like this:

João Silva

Does any one have any suggestions?

Tommy
  • 39,592
  • 10
  • 90
  • 121
Chico José
  • 121
  • 2
  • 16
  • [String.Split()](https://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx) and then combine the first and last items of the array. –  Apr 12 '16 at 12:08
  • @StephenMuecke is definitely the only possible solution. You have to split by " " space char. – Martino Lessio Apr 12 '16 at 12:09
  • 2
    Is this a SQL-Server or .NET question? What have you tried, what was the issue? What's with names like Abby Lee Jones? Is `Abby` or `Abby Lee` the firstname? – Tim Schmelter Apr 12 '16 at 12:10
  • This is in .net. I have tried when I recieve the person full name get the first and last name from the string. For example João Afonso Silva the first name will be João and the last name Silva. Then combine both. – Chico José Apr 12 '16 at 12:18
  • 2
    Only good way to solve this is during capture, require firstname and lastname fields and store them independently. Then retrieval is easy. Without that you cannot possibly determine the surname dynamically. – JL. Apr 12 '16 at 12:30
  • Is "Afonso de Santos Silva" the surname? Why not? If a human can't answer this question (without looking it up at the phone directory) a computer can't either. – Panagiotis Kanavos Apr 12 '16 at 12:32
  • The problem is that my client does not want "Afonso de Santos Silva" as last name. They only want "Silva" as last name witch complicates my issue. – Chico José Apr 12 '16 at 12:34
  • What are my first and last names? What about [Dick Van Dyke](https://en.m.wikipedia.org/wiki/Dick_Van_Dyke)? What about [some of these examples](http://stackoverflow.com/a/2385967/1364007)? Be **VERY** careful with how you handle edge cases. – Wai Ha Lee Apr 12 '16 at 21:27

2 Answers2

2

Fix your data storage and capturing.

I.E: In your DB schema have 2 fields: FirstName and LastName, and in your presentation layer, capture both fields independently.

In your question you claim that João Silva is the name you want. But this is wrong.

What you want is João (firstname) de Santos Silva (lastname). In your scenario you also need to capture the middlename (Afonso).

I would repair that first. Then what you want is trivial.

JL.
  • 78,954
  • 126
  • 311
  • 459
2

Just split on first and last.

string name = "João Afonso de Santos Silva";
string firstname = name.Split(' ').First();
string lastname = name.Split(' ').Last();