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

前端 未结 9 1141
眼角桃花
眼角桃花 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:07

    All the examples seem to make the other characters lowered first which isn't what I needed.

    customerName = CustomerName <-- Which is what I wanted

    this is an example = This Is An Example

    public static string ToUpperEveryWord(this string s)
    {
        // Check for empty string.  
        if (string.IsNullOrEmpty(s))
        {
            return string.Empty;
        }
    
        var words = s.Split(' ');
    
        var t = "";
        foreach (var word in words)
        {
            t += char.ToUpper(word[0]) + word.Substring(1) + ' ';
        }
        return t.Trim();
    }
    

提交回复
热议问题