Friday, January 16, 2009

Retrieving a Person's Last Name from a FullName field

I encountered a unique situation where a client's database table had usernames stored in a single "FullName" field, rather than the more common approach of having one field for the first name and another field for the last name. Restrictions within the company prevent this from ever being altered. Yet I needed a way to retrieve a person's last name, no matter how a name might be formatted.

Based on the possible data in their database, I wrote this code to accomplish this:

// A string containing a person's full name comes in 3 forms:
// 1. John Smith
// 2. John O. Smith
// 3. Smith, John [O.]
// This method returns just the last name.
public static string GetLastName(string fullName)
{
string lastName = "";
fullName = fullName.Trim();

if (fullName.Contains(",")) // Case #3
{
int idx = fullName.IndexOf(",");
lastName = fullName.Substring(0, idx);
}
else
{
int idx = fullName.IndexOf(" "); // Find the first space character
int idx2 = -1;
if (idx != -1)
idx2 = fullName.IndexOf(" ", idx + 1);

if (idx2 != -1) // Case #2
lastName = fullName.Substring(idx2 + 1);
else // Case #1
lastName = fullName.Substring(idx + 1);
}

return lastName;
}

No comments:

Post a Comment