C# Get Initials of DisplayName

Viewed 3913

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;
        }
4 Answers

Or just another variation as an extension method, with a small amount of sanity checking

Given

public static class StringExtensions
{
   public static string GetInitials(this string value)
      => string.Concat(value
         .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
         .Where(x => x.Length >= 1 && char.IsLetter(x[0]))
         .Select(x => char.ToUpper(x[0])));
}

Usage

var list = new List<string>()
{
   "James blerg Smith",
   "Michael Smith",
   "Robert Smith 3rd",
   "Maria splutnic Garcia", 
   "David Smith", 
   "Maria Rodriguez",
   "Mary Smith", 
   "Maria Hernandez"
};

foreach (var name in list)
   Console.WriteLine(name.GetInitials());

Output

JBS
MS
RS
MSG
DS
MR
MS
MH

Full Demo Here

How about the following:

   void Main()
{
    Console.WriteLine(GetInitials("John Smith"));
    Console.WriteLine(GetInitials("Smith, John"));
    Console.WriteLine(GetInitials("John"));
    Console.WriteLine(GetInitials("Smith"));
}

private string GetInitials(string name)
{
    if (string.IsNullOrWhiteSpace(name))
    {
        return string.Empty;
    }
    var splitted = name?.Split(' ');
    var initials = $"{splitted[0][0]}{(splitted.Length > 1 ? splitted[splitted.Length - 1][0] : (char?)null)}";
    return initials;
}

Output:

JS - SJ - J - S

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;           
    }

the code below is from here. what the code does is take the first letter of every word from the string and outputs it as capital letters.

   static void printInitials(String name) 
    { 
        if (name.Length == 0) 
            return; 
  
        // Since touuper() returns int, 
        // we do typecasting 
        Console.Write(Char.ToUpper(name[0])); 
  
        // Traverse rest of the string and  
        // print the characters after spaces. 
        for (int i = 1; i < name.Length - 1; i++) 
            if (name[i] == ' '&((i + 1)!=name.Length)) 
                Console.Write(" " + Char.ToUpper(name[i + 1])); 
    } 

Related