I'm trying to extract initials from a display name to be used to display their initials. I'm finding it difficult because the string is one value containing one word or more. How can I achieve this?
Example:
'John Smith' => JS
'Smith, John' => SJ
'John' => J
'Smith' => S
public static SearchDto ToSearchDto(this PersonBasicDto person)
{
return new SearchDto
{
Id = new Guid(person.Id),
Label = person.DisplayName,
Initials = //TODO: GetInitials Code
};
}
I used the following solution: I created a helper method which allowed me to test for multiple cases.
public static string GetInitials(this string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return string.Empty;
}
string[] nameSplit = name.Trim().Split(new string[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries);
var initials = nameSplit[0].Substring(0, 1).ToUpper();
if (nameSplit.Length > 1)
{
initials += nameSplit[nameSplit.Length - 1].Substring(0, 1).ToUpper();
}
return initials;
}
Simple and easy to understand code and handles names which contain first, middle and last name such as "John Smith William".
Test at: https://dotnetfiddle.net/kmaXXE
Console.WriteLine(GetInitials("John Smith")); // JS
Console.WriteLine(GetInitials("Smith, John")); // SJ
Console.WriteLine(GetInitials("John")); // J
Console.WriteLine(GetInitials("Smith")); // S
Console.WriteLine(GetInitials("John Smith William")); // JSW
Console.WriteLine(GetInitials("John H Doe")); // JHD
static string GetInitials(string name)
{
// StringSplitOptions.RemoveEmptyEntries excludes empty spaces returned by the Split method
string[] nameSplit = name.Split(new string[] { "," , " "}, StringSplitOptions.RemoveEmptyEntries);
string initials = "";
foreach (string item in nameSplit)
{
initials += item.Substring(0, 1).ToUpper();
}
return initials;
}