String.Capitalize in C# (PHP’s ucwords in C#)
I have been playing around with C# recently and found the need for functionality similar to that provided by PHP’s ucwords() function. I dont think this exists in C# as standard so here is a simple extension method to achieve ucwords in C# using a little bit of LINQ (the extremely useful Aggregate extension method) to achieve it:
public static string Capitalize(this String s)
{
return s.ToCharArray().Aggregate(String.Empty,
(working, next) =>
working.Length == 0 && next != ' ' ? next.ToString().ToUpper() : (
working.EndsWith(" ") ? working + next.ToString().ToUpper() :
working + next.ToString()
)
);
}
With this included in your name space, the extension method can be used on any String instance like:
string myString = "this sentence needs capitalization!"; Console.WriteLine(myString.Capitalize()); //This Sentence Needs Capitalization!
Short but sweet!
Posted by Daniel Skinner 2009-02-25 15:10:50
Categories: General
Tags: Aggeregate, c#, Extension Method, LINQ, php, ucwords




here is better way
http://www.aspdotnetfaq.com/Faq/How-to-Capitalize-the-First-Letter-of-All-Words-in-a-string-in-C-sharp.aspx
Comment by Pravin — March 19, 2009 @ 4:26 pm
That is also a possibility but the functionality of the two methods are not the same (in principle).
However, the behaviour of that method may change in the future. A more accurate ToTitleCase method would change “war and peace” to “War and Peace” and so the functionality of the ToTitleCase method will improve in future releases.
The Captialize function I provided is meant to change “war and peace” to “War And Peace”.
Comment by Daniel Skinner — March 22, 2009 @ 10:16 am
I suggest adding ToLower() the the last part so it also converts “tHIS sENTENCE” to “This Sentence” rather than “THIS SENTENCE.
i.e.
public static string Capitalize(this String s)
{
return s.ToCharArray().Aggregate(String.Empty,
(working, next) =>
working.Length == 0 && next != ‘ ‘ ? next.ToString().ToUpper() : (
working.EndsWith(” “) ? working + next.ToString().ToUpper() :
working + next.ToString().ToLower()
)
);
}
Comment by julio — October 7, 2009 @ 4:32 pm