How to capitalize the first character of each word, or the first character of a whole string, with C#?

前端 未结 9 1156
眼角桃花
眼角桃花 2020-11-29 05:27

I could write my own algorithm to do it, but I feel there should be the equivalent to ruby\'s humanize in C#.

I googled it but only found ways to humanize dates.

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 06:14

    If you just want to capitalize the first character, just stick this in a utility method of your own:

    return string.IsNullOrEmpty(str) 
        ? str
        : str[0].ToUpperInvariant() + str.Substring(1).ToLowerInvariant();
    

    There's also a library method to capitalize the first character of every word:

    http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx

提交回复
热议问题