[Solved] C# array string names change content order


First, let’s elaborate rules:

  1. One part "John" -> "John" (do nothing)
  2. Two parts "John Smith" -> "Smith, John" (last, first)
  3. Three+ parts "John Peter Jack Smith" -> "Smith, John P. J." (last, first, other in order as single letters)

Having these rules we can implement a simple reordering:

private static String ReOrderNamesParts(string name) {
  if (string.IsNullOrEmpty(name))
    return name;

  string[] parts = name.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

  if (parts.Length <= 0)
    return name;

  StringBuilder sb = new StringBuilder(parts[parts.Length - 1]);

  if (parts.Length > 2) {
    sb.Append(", ");
    sb.Append(parts[0]);
  }

  for (int i = 1; i < parts.Length - 1; ++i) {
    sb.Append(' ');
    sb.Append(parts[i].Substring(0, 1));
    sb.Append('.');
  }

  return sb.ToString();
}

And so you can put

string[] names = { "Paul Page Load Wood", "Michael Kraiser Unter", "Mia Rock Spark" };

for (int i = 0; i < names.Length; ++i)
  names[i] = ReOrderNamesParts(names[i]);

Or if you want just to print out:

Console.Write(String.Join(Environment.NewLine, 
  names.Select(name => eOrderNamesParts(names))));

1

solved C# array string names change content order