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

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

    I have achieved the same using custom extension methods. For First Letter of First sub-string use the method yourString.ToFirstLetterUpper(). For First Letter of Every sub-string excluding articles and some propositions, use the method yourString.ToAllFirstLetterInUpper(). Below is a console program:

    class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("this is my string".ToAllFirstLetterInUpper());
                Console.WriteLine("uniVersity of lonDon".ToAllFirstLetterInUpper());
            }
        }
    
        public static class StringExtension
        {
            public static string ToAllFirstLetterInUpper(this string str)
            {
                var array = str.Split(" ");
    
                for (int i = 0; i < array.Length; i++)
                {
                    if (array[i] == "" || array[i] == " " || listOfArticles_Prepositions().Contains(array[i])) continue;
                    array[i] = array[i].ToFirstLetterUpper();
                }
                return string.Join(" ", array);
            }
    
            private static string ToFirstLetterUpper(this string str)
            {
                return str?.First().ToString().ToUpper() + str?.Substring(1).ToLower();
            }
    
            private static string[] listOfArticles_Prepositions()
            {
                return new[]
                {
                    "in","on","to","of","and","or","for","a","an","is"
                };
            }
        }
    

    OUTPUT

    This is My String
    University of London
    Process finished with exit code 0.
    

提交回复
热议问题