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.
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.
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.
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:
- I believe it’s easier to read, but readability is very subjective.
- 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.
Please let me know if you can think up other implementations for capitalizing letters.