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!



4 Comments
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
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”.
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()
)
);
}
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()
)
);
}