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

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

    0 讨论(0)
  • 2020-11-29 06:22

    As discussed in the comments of @miguel's answer, you can use TextInfo.ToTitleCase which has been available since .NET 1.1. Here is some code corresponding to your example:

    string lipsum1 = "Lorem lipsum et";
    
    // Creates a TextInfo based on the "en-US" culture.
    TextInfo textInfo = new CultureInfo("en-US",false).TextInfo;
    
    // Changes a string to titlecase.
    Console.WriteLine("\"{0}\" to titlecase: {1}", 
                      lipsum1, 
                      textInfo.ToTitleCase( lipsum1 )); 
    
    // Will output: "Lorem lipsum et" to titlecase: Lorem Lipsum Et
    

    It will ignore casing things that are all caps such as "LOREM LIPSUM ET" because it is taking care of cases if acronyms are in text (so that "NAMBLA" won't become "nambla" or "Nambla").

    However if you only want to capitalize the first character you can do the solution that is over here… or you could just split the string and capitalize the first one in the list:

    string lipsum2 = "Lorem Lipsum Et";
    
    string lipsum2lower = textInfo.ToLower(lipsum2);
    
    string[] lipsum2split = lipsum2lower.Split(' ');
    
    bool first = true;
    
    foreach (string s in lipsum2split)
    {
        if (first)
        {
            Console.Write("{0} ", textInfo.ToTitleCase(s));
            first = false;
        }
        else
        {
            Console.Write("{0} ", s);
        }
    }
    
    // Will output: Lorem lipsum et 
    
    0 讨论(0)
  • 2020-11-29 06:27

    There is another elegant solution :

    Define the function ToTitleCase in an static class of your projet

    using System.Globalization;
    
    public static string ToTitleCase(this string title)
    {
        return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(title.ToLower()); 
    }
    

    And then use it like a string extension anywhere on your project:

    "have a good day !".ToTitleCase() // "Have A Good Day !"
    
    0 讨论(0)
提交回复
热议问题