Capitalizing words in a string using c#

前端 未结 10 1320
攒了一身酷
攒了一身酷 2020-12-16 11:22

I need to take a string, and capitalize words in it. Certain words (\"in\", \"at\", etc.), are not capitalized and are changed to lower case if encountered. The first word s

10条回答
  •  南方客
    南方客 (楼主)
    2020-12-16 12:16

    Depending on how often you plan on doing the capitalization I'd go with the naive approach. You could possibly do it with a regular expression, but the fact that you don't want certain words capitalized makes that a little trickier.

    Edit:

    You can do it with two passes using regexes

    var result = Regex.Replace("of mice and men isn't By CNN", @"\b(\w)", m => m.Value.ToUpper());
    result = Regex.Replace(result, @"(\s(of|in|by|and)|\'[st])\b", m => m.Value.ToLower(), RegexOptions.IgnoreCase);
    

    This outputs Of Mice and Men Isn't by CNN.

    The first expression capitalizes every letter on a word boundary and the second one downcases any words matching the list that are surrounded by whitespace.

    The downsides to this approach is that you're using regexs (now you have two problems) and you'll need to keep that list of excluded words up to date. My regex-fu isn't good enough to be able to do it in one expression, but it might be possible.

提交回复
热议问题