Convert all first letter to upper case, rest lower for each word

前端 未结 11 2076
一向
一向 2020-12-04 10:15

I have a string of text (about 5-6 words mostly) that I need to convert.

Currently the text looks like:

THIS IS MY TEXT RIGHT NOW

I

11条回答
  •  春和景丽
    2020-12-04 10:43

    When building big tables speed is a concern so Jamie Dixon's second function is best, but it doesn't completely work as is...

    It fails to take all of the letters to lowercase, and it only capitalizes the first letter of the string, not the first letter of each word in the string... the below option fixes both issues:

        public string UppercaseFirstEach(string s)
        {
            char[] a = s.ToLower().ToCharArray();
    
            for (int i = 0; i < a.Count(); i++ )
            {
                a[i] = i == 0 || a[i-1] == ' ' ? char.ToUpper(a[i]) : a[i];
    
            }
    
            return new string(a);
        }
    

    Although at this point, whether this is still the fastest option is uncertain, the Regex solution provided by George Mauer might be faster... someone who cares enough should test it.

提交回复
热议问题