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!

This entry was posted in General and tagged , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

4 Comments

  1. Pravin
    Posted March 19, 2009 at 4:26 pm | Permalink
  2. Posted March 22, 2009 at 10:16 am | Permalink

    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”.

  3. Posted October 7, 2009 at 4:32 pm | Permalink

    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()
    )
    );
    }

  4. Posted April 15, 2010 at 8:49 am | Permalink

    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()
    )
    );
    }

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>