Vadim's Weblog

Never stop learning.

Posts Tagged ‘capitalize’

Capitalize only first character. (C#)

Posted by Vadim on October 9, 2013

Once in a while, you may need need to capitalize only the first character of a word. Like everything else in programming, there’s more than one way to solve this problem. In this post, I’m going to explore three different ways to capitalize the first letter of a word, and then let you know which one I prefer.

1. String manipulation solution.
private string UpperFirst(string text)
{
return char.ToUpper(text[0]) +
((text.Length > 1) ? text.Substring(1).ToLower() : string.Empty);
}

 

This solution is straightforward. First, capitalize the initial character of the text, and then append the rest. Next, we test if our text has more than 1 character. If this is text with multiple characters, we convert the rest of the text to lowercase, in case there are any uppercase letters.

2. LINQ solution.
private string UpperFirst(string format)
{
return format.First().ToString().ToUpper() +
String.Join("", format.Skip(1)).ToLower();
}

 

LINQ solution is also easy to follow and understand. We get the first character, and then we convert it to String (because the char type doesn’t have instance implementation of ToUpper()). Then, like in the previous solution, we append the rest of text.

3. TextInfo.ToTitleCase solution.
private string UpperFirst(string text)
{
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text.ToLower());
}

 

This solution is taking advantage of the ToTitleCase method. It looks simple, but it’s not exactly like our two previous solutions. The problem with this solution is that it’s going to capitalize every word in the text.  For example: if your text has the value “hello world”, the result of this solution will be “Hello World” and not “Hello world” as in the two earlier examples. If you need to capitalize every word in your text, use this solution. Otherwise, use one of the earlier solutions.

The best solution for me.

Personally, the 1st solution looks the best. There are two reasons why I think solution #1 is the best:

  1. I believe it’s easier to read, but readability is very subjective.
  2. It performs better. I iterated each solution 1,000,000 times, and the first solution performed the fastest.

Below is the table of my performance test, in case you’re interested. It shows the time in milliseconds for 1,000,000 iterations.

Solution Time
String manipulation

201

LINQ

511

TextInfo.ToTitleCase

361

 

Please let me know if you can think up other implementations for capitalizing letters.

Technorati Tags: ,,,

Posted in C# | Tagged: , , , | 3 Comments »