Categories Tags

Title Case

Problem:

Capitalizing the first character of each word in a string (i.e. “the final countdown” → “The Final Countdown”).

Solution:

C#:

C# has a built-in function for this. Its called ‘toTitleCase’, hidden deep within the System.Globalization namespace.

So how do you use it?


using System.Globalization;
 
...
// Get the instance of the TextInfo class to use to (no constructor), comes from the current thread
TextInfo info = (System.Threading.Thread.CurrentThread.CurrentCulture).TextInfo;
 
string sample = "hello world";
 
// Print to console the title case
// Outputs: Hello World
Console.WriteLine(info.ToTitleCase(sample));

The ‘ToTitleCase’ function returns an instance of a string which will have all of the first characters in words changed to upper case, and leaves the rest of the text as is. This means that if a word is in all capital letters it will remain that way. A simple work around for this is to call the string object’s ‘ToLower’ function before we send the string into the ‘ToTitleCase’ function.

For example,

using System.Globalization;
 
...
// Get the instance of the TextInfo class to use to (no constructor), comes from the current thread
TextInfo info = (System.Threading.Thread.CurrentThread.CurrentCulture).TextInfo;
 
string sample = "HELLO world";
 
// Print to console the title case
// Emits: HELLO World
Console.WriteLine(info.ToTitleCase(sample));
 
// Pre-lowercase everything
// Emits: Hello World
Console.WriteLine(info.ToTitleCase(sample.ToLower()));

PHP:

The PHP version of this function is a fair bit easier to get to.  PHP’s function is called ‘ucwords’.  However, similar to the C# version you should always have the string sent in in lower case if you want it to only make the first character of each word upper case (it only changes the first character and doesn’t touch the others).


// Outputs: The Final Countdown
echo ucwords('the final countdown');

Posted in programming

Tags: