Dot Net Perls

Uppercase First Letter in String - C#

by Sam Allen

Problem

You want to capitalize your string by uppercasing the first letter, and then return it with the remaining part unchanged. Basically, you need the ucfirst function from PHP and Perl, which has the following results.

InputOutput
samuelSamuel
juliaJulia
john smithJohn smith
It does not uppercase each word.

Solution: capitalizing strings in C#

In this article, I am going to show you an example and benchmark of a C# method that uppercases the first letter. The method first here is the slower of the two.

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine(UppercaseFirst("samuel"));
        Console.WriteLine(UppercaseFirst("julia"));
        Console.WriteLine(UppercaseFirst("john smith"));
        // Samuel
        // Julia
        // John smith
    }

    static string UppercaseFirst(string s)
    {
        // Check for empty string.
        if (string.IsNullOrEmpty(s))
        {
            return string.Empty;
        }
        // Return char and concat substring.
        return char.ToUpper(s[0]) + s.Substring(1);
    }
}
  1. It receives the string argument.
    This method takes in a string as a parameter.
  2. It checks for null and empty.
    We check for null or empty strings and return "" if that is true. [C# - Empty Strings - dotnetperls.com]
  3. It uses ToUpper.
    It gets the uppercase first character of the string it received. Then it combines this with a substring of all characters after that.
  4. It returns the complete string.
    It concatenates the two above values and returns the result. [C# - String Concat Samples - dotnetperls.com]

Information: improving the string uppercase method (2)

I investigated ToCharArray and its performance impact on this sort of character-based method. The following is the faster version, and it returns the same results.

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine(UppercaseFirst("samuel"));
        Console.WriteLine(UppercaseFirst("julia"));
        Console.WriteLine(UppercaseFirst("john smith"));
        // Samuel
        // Julia
        // John smith
    }

    static string UppercaseFirst(string s)
    {
        if (string.IsNullOrEmpty(s))
        {
            return string.Empty;
        }
        char[] a = s.ToCharArray();
        a[0] = char.ToUpper(a[0]);
        return new string(a);
    }
}
  1. It receives the string.
    It receives a string in the same way as the previous example.
  2. It checks for null or empty.
    The method then checks for null or empty and returns an empty string if true.
  3. It uses ToCharArray.
    ToCharArray converts the string into a char value array, which we can change in-place. [C# - Char Array Performance - dotnetperls.com]
  4. It uppercases the first char.
    We call char.ToUpper on the first character in that array, and then finally return a new string formed from the char[] array.

Information: benchmarking method 1 and method 2

Here are my results from testing 1,000,000 iterations of these functions in a loop over the string "michael". This test is in my ASP.NET application, so the environment is the same as it will be in my ASP.NET app as it is updated on the Internet.

The second approach is faster because it only allocates one new string in the return statement. The first approach allocates two strings: the Substring(1), and then a new string with string.Concat. [See string.Concat link above]

Summary: uppercasing the first letter

These methods are valuable tools in your arsenal as a .NET developer. They are useful for database results that may not be formatted correctly. Custom logic for names such as "McCain" and "DeGeneres" can be added.

Normally, the performance requirements are not strict when you use this kind of code, but occasionally the benchmarks here may be useful. They can also help us understand how strings work in C#: they are immutable.

Dot Net Perls
About
Sitemap
Source code
RSS
Strings
Split String Examples
IndexOf String Examples
Remove HTML Tags From String
Count Characters in String
Uppercase First Letter in String
Recent
Pi
NGEN Installer Class
List Element Equality
DateTime Tips and Tricks
Remove HTML Tags From String
© 2008 Sam Allen. All rights reserved.