public static Name ParseName(this string input) { /*--- Inits ---*/ var words = input.Split( new char[] {' ', ',' }, StringSplitOptions.RemoveEmptyEntries ) .ToList(); var n = words.Count; /*--- Special Cases ---*/ if (n == 0) { return new Name(); } if (n == 1) { return new Name { First = words[0] }; } /*--- No Comma ---*/ if (!input.Contains(",")) { var result = new Name { First = words[0], Last = words[n - 1] }; if (n > 2) { result.Middle = string.Join(' ', words.Skip(1).Take(n - 2)); } return result; } /*--- Comma After First Word ---*/ if (input.IndexOf(',') < input.IndexOf(' ')) { var result = new Name { Last = words[0], First = words[1] }; result.Middle = string.Join(' ', words.Skip(2)); return result; } /*--- Comma Later ---*/ var suffixes = new List<string>() { "JR.", "JR", "SR.", "SR", "III", "IV" }; if (suffixes.Contains(words[n-1].ToUpperInvariant())) { var result = string.Join(' ', words.Take(n - 1)).ParseName(); result.Suffix = words[n - 1]; return result; } /*--- Contains Comma Later, But No Matching Suffix ---*/ { words = input .Split(',', StringSplitOptions.RemoveEmptyEntries) .ToList(); n = words.Count(); if (n == 0) { return new Name(); } var result = new Name { Last = words[0] }; result.First = string.Join(' ', words.Skip(1)); return result; } } public class Name { public Name() { First = string.Empty; Middle = string.Empty; Last = string.Empty; Suffix = string.Empty; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } }
ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.