How to Capitalize names

前端 未结 9 1801
余生分开走
余生分开走 2020-12-15 02:46

so basically if i want to transform a name from

stephen smith 

to

Stephen Smith

i can easily do it with c

9条回答
  •  攒了一身酷
    2020-12-15 03:09

    A slight extension on the answer offered by Pedro:

    Regex.Replace(Name, @"(?:(M|m)(c)|(\b))([a-z])", delegate(Match m) { 
        return String.Concat(m.Groups[1].Value.ToUpper(), m.Groups[2].Value, m.Groups[3].Value, m.Groups[4].Value.ToUpper());
     });
    

    This will correctly capitalize McNames in addition to title case. eg "simon mcguinnis" --> "Simon McGuinnis"

    • The first non-capture group will match any word-break character OR "Mc" / "mc".
    • If it matches a word-break, then groups 1 and 2 are empty and group 3 contains that character.
    • If it matches "Mc" or "mc" the groups 1 and 2 contain "m" and "c" and group 3 is empty.

      • Group 1 (the "m" or "M") is capitalized.
      • Group 2 (the "c") remains un-altered.
      • Group 3 (the break character) remains un-altered.
      • Group 4 (the first letter of the next word) is capitalized.

    All 4 groups, empty or otherwise, are concatenated to generate the return string.

提交回复
热议问题