Tag: Extension Method

25
Feb

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!